当前位置:网站首页>Recursion: depth first search
Recursion: depth first search
2022-07-03 03:32:00 【My family Dabao is the cutest】
The maximum depth of a binary tree
The problem of binary tree usually gives priority to recursion , We want to ask for the depth of a tree , When we know the depth of the left subtree and the right subtree , that root The depth of the node is the maximum value of the left and right subtrees plus 1
d e p t h ( r o o t ) = m a x ( d e p t h ( r o o t . l e f t ) , d e p t h ( r o o t . r i g h t ) ) + 1 depth(root)=max(depth(root.left),depth(root.right))+1 depth(root)=max(depth(root.left),depth(root.right))+1
Obviously, this is also a recursive formula , So you can use recursion directly
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if not root: # base case
return 0
l = dfs(root.left) # First find the depth of the left subtree
r = dfs(root.right) # Then find the depth of the right subtree
return max(l,r)+1 # The lion , And then add root The node is +1
return dfs(root)
Minimum depth of binary tree
At first, I felt that the minimum depth was the same as the maximum depth , But find it written directly min There is a problem .
The most important question is , The minimum depth is from the leaf node , therefore base case There are two kinds of , One is head==None, The other way is head.right is None and head.left is None. It must start from the leaf node .
Wrong writing , You can see a node ,a The left subtree depth of the node is 0, The depth of the right subtree is 2, Then according to the recursive formula of this error, we can get a The minimum depth of the node is min(0,2)=0, But obviously ,a Node is not a leaf node , So we can't find the minimum depth . But the maximum depth will not have such a problem .
class Solution:
def minDepth(self, root: TreeNode) -> int:
if root is None:
return 0
return min(self.minDepth(root.right),self.minDepth(root.left))+1

To write correctly, you need to consider that a subtree is None The situation of , At this time, we need to recurse the subtree on the other side as the minimum depth .
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if root is None:
return 0
elif root.left is None and root.right is None:
return 1
elif root.left is None:
return self.minDepth(root.right)+1
elif root.right is None:
return self.minDepth(root.left) + 1
else:
return min(self.minDepth(root.right),self.minDepth(root.left))+1
Balanced binary trees
Given a binary tree , Determine if it's a highly balanced binary tree .
In this question , A height balanced binary tree is defined as :
Every node of a binary tree The absolute value of the height difference between the left and right subtrees is not more than 1
The essence of this problem is to solve the depth of the tree , It is only required that the depth difference between the left and right subtrees should not exceed 1, If it exceeds one, it will return directly False. The same understanding , We want to know root Nodes are balanced , Then we need to calculate the height of the left and right subtrees , After calculating the height , We also need to judge whether the left and right subtrees are also balanced binary trees , If one is not , that root Certainly not
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def dfs(root):
if not root:
return 0,True
l,lf = dfs(root.left)
r,rf = dfs(root.right)
if abs(l-r) <= 1 and lf and rf:
return max(l,r)+1,True
else:
return max(l,r)+1,False
_,f = dfs(root)
return f
The number of nodes in a complete binary tree
Counting numbers is also very simple , We count the number of left subtrees and then add the number of right subtrees , Then add the root node to get the total number of nodes .
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if root is None:
return 0
return self.countNodes(root.left) + self.countNodes(root.right) + 1
边栏推荐
- numpy之 警告VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
- Use of El tree search method
- Applet (continuous update)
- 将时间戳转为指定格式的时间
- VS 2019配置tensorRT
- The series of hyperbolic function in daily problem
- UMI route interception (simple and rough)
- VS code配置虚拟环境
- MongoDB基本操作【增、删、改、查】
- ffmpeg之 一张/多张图片合成视频
猜你喜欢
![MySQL practice 45 lecture [transaction isolation]](/img/a5/5420651d6be51e892976f02be8c43c.png)
MySQL practice 45 lecture [transaction isolation]

Pytoch configuration

900W+ 数据,从 17s 到 300ms,如何操作

Pytorch multi card distributed training distributeddataparallel usage

MongoDB簡介

Don't use the new Dede collection without the updated Dede plug-in

Ffmpeg one / more pictures synthetic video

The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
![C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions](/img/4a/1df03d9f3315debb4c335260ed39f2.jpg)
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions

npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
随机推荐
C# WebRequest POST模式 ,基于“Basic Auth”口令认证模式,使用multipart/form-data方式上传文件及提交其他数据
The idea cannot be loaded, and the market solution can be applied (pro test)
[mathematical logic] propositions and connectives (propositions | propositional symbolization | truth connectives | no | conjunction | disjunction | non truth connectives | implication | equivalence)
QQ小程序开发之 一些前期准备:预约开发账号、下载安装开发者工具、创建qq小程序
Pytorch multi card distributed training distributeddataparallel usage
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
Pat class B "1104 forever" DFS optimization idea
递归:快速排序,归并排序和堆排序
基于Qt的yolov5工程
Bigvision code
The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
Mongodb master profile
Converts a timestamp to a time in the specified format
ffmpeg录制屏幕和截屏
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post
Yolov5 project based on QT
MongoDB簡介
QT based tensorrt accelerated yolov5
UMI route interception (simple and rough)