Tree and Divide Conquer

联想服务器ThinkSystemRAID阵列设置教程 关注我不迷路,全是干货! 以联想ThinkSystemSR530为例子进行示范。 开机点按【F1】 点击——【UEFI设置】 依次点击——【系统设置】——【存储】 点击——【RAID卡】 PS:本次服务器配置的是730-8i 阵列卡,按实际情况选中需要设置的阵列卡即可。 点击——【Main Menu】 点击——【Configuration Management】 点击——【Create Virtual Drive】 点击——【Select RAID Leve.. 阅读详情

title: Tree and Divide Conquer
date: 2020-03-24 20:11:09
tags: Algorithm


Tree and Divide Conquer

最近做二叉树相关的题,被递归搞的晕头转向。

一、树的性质

参考:Tree总结

由于树的结构,这种数据结构很适合用分治(Divide Conquer)

Divide and Conquer模版

递归算法模版;

def traversal(root):
	# base case(none or leaf)
	if not root:
		# do sth
	
	# divide
	left = traversal(root.left)
	right = traversal(root.right)
	
	# Conquer
	res = # merge 
	return res

114 Flatten Binary Tree to Linked List

以 leetcode #114题为例

1)从最简单的case开始

simplest case,树只有一个元素1,直接返回;

# simplest case:
    1
# 两个元素:
    1
   / 
  2   
  ########   
    1
     \
      2
# 三个元素:
    1
   / \
  2   3
# N 个元素
     1
   /   \
LTree  RTree
例子:
    1
   / \
  2   5
 / \   \
3   4   6

当有两个元素时:

def flatten2(root):
    left = root.left
    right = root.right
    if left:
        root.right = left
        root.left = None

当有三个元素时:

def flatten3(root):
    # divide 
    left = root.left
    right = root.right
    # merge
    if left:
        root.right = left
        root.left = None
    if right:
        left.right = right
2)一般case

可以将其分为 左子树和右子树,(假设左右都为三个元素(base case),我们可以用上面的程序处理好)。假设左右子树都已经处理完毕。

def flatten(root):
	# base case(none)
    if not root:
        return
    # leaf node
    if not root.left and not root.right:
        return root
    # divide
   	left = root.left
    right = root.right
    # conquer 处理左右子树
    flatten(left)
    flatten(right)
    # merge
    if left:
        root.right=left
        root.left = None
    if right:
        ...
3) merge

如何把子问题的解merge原问题的解?

把子问题的解 merge成问题的解时需要解决一个问题,即如何将右子树链接到左子树的后面?

  1. 左子树的哪个节点去链接右子树根节点?
  2. 如何确定这个节点的位置

根据题意知道,最终生成 linked list 顺序是先序遍历的顺序,故将左子树最右边的叶子节点链接到右子树的根节点;使用python中的全局变量指向当前根节点下的最右叶子节点。

算法:

 prev = None
 def func(root):
 	if root is leaf:
 		# prev 指向左子树的最右子节点
 		prev=root
    left = root.left
    right = root.right
    # 递归处理左子树
    func(left)
    # 如果左子树存在
    if left:
    	# 将root的右子节点指向左子树
    	root.right = left
    	root.left = None
    	# 将左子树最右边的叶子节点指向右子树
    	prev.right = right
    # 递归处理右子树
    func(right)

最终AC的代码:

Python3代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def __init__(self):
        self.prev = None
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        # base case
        if not root:
            return
        if not root.left and not root.right:
            self.prev=root
            return
       	# divide
        left = root.left
        right = root.right
        # conquer
        self.flatten(left)
        # merge
        if left:
            root.right, root.left = left, None
            self.prev.right = right
        # conquer
        self.flatten(right)

代码精简版:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def __init__(self):
        self.prev = None
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        self.prev = root
        right = root.right
        self.flatten(root.left)
        root.right, root.left=root.left, None
        self.prev.right = right
        self.flatten(right)

从以上代码可以看出,其实就是对 Tree 进行先序遍历,同时将全局变量用作指针

这道题还有其他思路,(修改版的后序遍历)遍历顺序是右子树->左子树->根节点。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def __init__(self):
        self.prev = None
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return None
        self.flatten(root.right)
        self.flatten(root.left)

        root.right = self.prev
        root.left = None
        self.prev = root
总结
  1. 对树进行divide conquer ,要把所有的最简单case列出来分析
  2. 将树分为子问题一般比较容易,关键如何将子问题的解merge成原问题的解!
  3. python的全局变量的使用。
地质工程师必备:Dips软件从数据导入到主结构面分析的完整流程解析 本文详细解析了地质工程师使用Dips软件进行主结构面分析的完整流程。从数据准备与导入、结构面分组与扇形区划分,到主结构面计算与工程解读,系统阐述了如何将野外节理数据转化为控制岩体稳定性的关键信息。重点介绍了利用等值线图识别优势组、计算统计主值及其置信椭圆,并强调了地质判断与工程应用结合的重要性。 阅读详情

相关推荐

node-red 可视化探索

配置socket选择配置流程产生url。

weixin_44133581的博客 3422

[LeetCode] 系统刷题4_Binary Tree & Divide and Conquer

参考[LeetCode] questions conlusion_InOrder, PreOrder, PostOrder traversal可以对binary tree进行遍历。 此处说明Divide and Conquer 的做法,其实跟recursive的做法很像,但是将结果存进array并且输出,最后conquer (这一步worst T:O(n)) 起来,所以时间复杂度可以从遍...

weixin_30275415的博客 150

【IC设计实战】去耦电容decap在电源完整性中的关键作用与选型策略

本文深入探讨了去耦电容(decap)在IC设计电源完整性中的核心作用。文章分析了decap如何通过提供本地电荷缓冲来抑制电源噪声与电压波动,并详细阐述了其选型与布局策略,包括MIM、MOM、MOS电容的特性对比,以及如何权衡峰值抑制与建立速度的矛盾,为设计稳定可靠的芯片电源系统提供实践指导。

weixin_29233857的博客 258

LintCode - Binary Tree & Divide and Conquer

Traverse the Binary Tree preorder  (visit, left, right) Binary Tree Preorder Traversal [easy] inorder     (left, visit, right) Binary Tree Inorder Traversal [easy] postorder(left, right, visit) ...

real_lisa的博客 273

AD9361 官方例程

文章目录一、官方资料1.1 介绍1.2 下载 和 使用1.3 相关资料二、步骤2.1 在Vivado中构建HDL2.2 在SDK中构建No- OS总结 一、官方资料 1.1 介绍 HDL参考设计介绍:AD9361 HDL Reference Designs 无操作系统介绍:AD9361 No-OS Software 1.2 下载 和 使用 HDL下载:Download HDL 在Vivado中构建HDL:Building HDL No-OS下载:Download No-OS 1.3 相关资料 AD

weixin_44630490的博客 3万+

第一章 EB安装

1.DemoWorkspace 是基于EB当前组件配置下的例程,包含了启动文件和中断服务函数以及组件demo。2.Mclsar 下存放的是EB的插件包和静态MCAL的驱动文件。

舊梦的博客 1997

[P3806] Divide and Conquer on Tree

Link: P3806 传送门 Solution: 询问树上是否存在两点间的距离为$k$,共有$m$次询问($m\le 100,k\le 1e7$) 预处理出所有距离的可能性再$O(1)$出解的复杂度为$O(n^2*log(n))$,明显TLE(但好像并不会) 而如果直接在线处理要分治$m$次,找$m$次完全相同的重心,完全没有必要 因此最好采用离线处理的方式 在每个点运用$s...

weixin_30544657的博客 84

少儿学编程系列--使用递归画出龙形曲线DragonCurve

龙形曲线(Dragon Curve) 龙形曲线(Dragon Curve)又叫分形龙,是一种自相似碎形曲线的统称,因形似龙的蜿蜒盘曲而得名 使用黄金比例画龙形曲线 根据黄金比例画一条龙曲线。每次递归,第一步向左转32.89度,移动0.74倍原距离;第二个递归步骤向右转46.99度,移动原来距离的0.55倍。请查看这个网页(https://larryriddle.agnesscott.org/ifs/heighway/goldenDragon.htm)了解关于龙形黄线数学的细节 龙形曲线效果 .

penriver的博客 2309

LeetCode 110. Balanced Binary Tree | DFS Divide and Conquer Python

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ cla...

real_lisa的博客 167

基于matlab实现的水果识别系统设计

本项目针对多种常见水果混合的图像,利用 Matlab 软件,对水果的识别进行研究。根据水果和背景的差别选取阈值,对去噪增强对比度后的图像进行二值化处理。再对图像进行边缘检测,选定连通区域,标记后再对不同种水果的颜色,形状,大小等特征进行快速识别水果,从而实现对水果的正确分拣。:水果识别、MATLAB、数字图像处理。

热情、奔放、快乐编程! 4866

Xinference新手指南(一个命令直接安装成功)

对于新手,必须得学会使用docker部署,这是基本功!这里就不过多去介绍了,如果评论要出教程的话,以后再出了。

Ven%的博客 827

分治法——树的遍历(Divide and Conquer - Tree Traversal)

分治法——树的遍历(Divide and Conquer - Tree Traversal)二叉树概念(Binary Tree Concepts) This is a binary tree with height h = 4. 口 represents empty tree with height h = -1. 口 is an external node only at level h a

UoM_XiaoShuaiShuai的博客 1291

黑猫带你学eMMC协议第9篇:eMMC初始化过程(initial)

本文依据eMMC JEDEC5.1及个人工作经验整理而成,如有错误请留言。 文章为个人辛苦整理,付费内容,禁止私自转载。 文章所在专栏:《黑猫带你学:eMMC协议详解》 1 什么是emmc的初始化 对于小白来说,可能不太明白什么是emmc初始化。举个栗子:当你拿到一个电脑,接上电源,是不是就立马可以用了呢?并不是吧,你还需要去开机,等待电脑启动,配置完各种参数,等出现了电脑桌面,你才能用。那么同样,对于emmc芯片来说,也不是提供电源就能用了,需要输入各种命令后,让其进入到tran state后,才能正.

黑猫奥利奥的博客 6755

【刷(shui)题记录】201812 艰难前行的一月

【前言】 NOIP过去,无缘WC。 有些迷茫,有些害怕。 GDKOI,不到一个月。GDOI,不到四个月。 愿不负青春。 这里一个星期考了二检。 12.8 CF936E——Divide_Conquer——Dynamic_Tree_Divide 12.9 CF749E——Math——Probability&Expectation 12.10 UOJ55——Divide_Conquer——Dyn...

MEET YOU FIRST TIME 300

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

[LeetCode] 236. Lowest Common Ancestor of a Binary Tree_ Medium tag: DFS, Divide and conquer

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to thedefinition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p...

weixin_30314631的博客 76

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

【Leetcode】Largest Rectangle in Histogram #84

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width o

zhixin_wen95的博客 229

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

[LeetCode] 124. Binary Tree Maximum Path Sum_ Hard tag: DFS recursive, Divide and conquer

Given anon-emptybinary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connectio...

weixin_30293135的博客 70

109. Convert Sorted List to Binary Search Tree (List; Divide-and-Conquer, dfs)

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. /** * Definition for singly-linked list. * struct ListNode { * int val; * ...

weixin_30556161的博客 73

108.Convert Sorted Array to Binary Search Tree(Array; Divide-and-Conquer, dfs)

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 思路:使用二分法,将list的中间节点作为根节点,然后分别处理list左半边及右半边,以此递归。 struct TreeNode { int val; TreeNode *left...

weixin_30762087的博客 77

P2634 [国家集训队]聪聪可可 - 点分治换根 or 树形dp

题目链接;https://www.luogu.com.cn/problem/P2634 题目大意: 思路:树形dp的题解:https://blog.csdn.net/qq_21433411/article/details/90180495 如果我们用点分治。换根统计之前的子树dp[i]表示之前子树路径%3=i的路径条数。tem[i]目前这棵树路径%3=i的路径条数;然后组合一下就可以了。 #in...

H_ang的博客 243

noiac132 B君的第三题 (树形dp)

传送门 本来想用点分治做,结果root又求不对 算的时候还算错了 我好菜啊 结果szr大佬告诉我是树形dp 我好菜啊!! 我们有$\lceil \frac{x}{k} \rceil = \frac{x+(k-x)\%k}{k}$ 于是可以把这个拆成两部分来求,最后加在一起再除个k 距离和很好求,连接x和fa[x]的边的贡献就是$size[x]*(N-size[x])$ 然后...

weixin_30549657的博客 78

用于目标导向规划的分治蒙特卡洛树搜索(论文解释)

Divide and Conquer Monte Carlo Tree Search for Goal Directed Planning 论文摘要 这篇论文介绍了一种名为“分治蒙特卡洛树搜索”的规划算法,它采用了一种非传统的方式进行规划。论文作者来自DeepMind、马克斯·普朗克研究所和Eta。 算法原理: 目标导向: 算法需要一个明确的目标,每次运行时目标可以不同。 规划: 算法不需要直接...

YannicKilcher的博客 525

洛谷 P2634 聪聪可可 —— 树形DP / 点分治

题目:https://www.luogu.org/problemnew/show/P2634 今天刚学了点分治,做例题; 好不容易A了,结果发现自己写的是树形DP...(也不用找重心)(比点分治快) #include<iostream> #include<cstdio> #include<cstring> #include<a...

aodan5477的博客 185

Detailed Explanation of LeetCode Problem 236: Lowest Common Ancestor of a Binary Tree

【代码】Detailed Explanation of LeetCode Problem 236: Lowest Common Ancestor of a Binary Tree。

码中鲸鱼????的博客 433

漫谈算法(四)分治算法 Divide and Conquer Algorithm

http://www.cnblogs.com/Gavin_Liu/archive/2011/04/15/2015469.html 先看一段来自wikipedia的定义:http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm Divide and conquer (D&C) is an important algorithm

学习之路 654

Divide and Conquer题解

第一题 You are interested in analyzing some hard-to-obtain data from two separate databases. Each database contains n numerical values, so there are 2n values total and you may assume that no two values...

clever_wr的博客 3067
上一篇: Pytorch 孪生lstm 句子相似性
下一篇: BFS DFS 判断DAG(有向无环图)
StarLib
博客等级 码龄8年 31粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值