当前位置:网站首页>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
边栏推荐
- Spark on yarn resource optimization ideas notes
- Basic operations of mongodb [add, delete, modify, query]
- 小程序获取用户头像和昵称
- Pytorch配置
- Don't use the new Dede collection without the updated Dede plug-in
- [set theory] partial order relation (partial order relation definition | partial order set definition | greater than or equal to relation | less than or equal to relation | integer division relation |
- Docker install and start MySQL service
- 使用InputFilter限制EditText时踩坑及解决方案
- shardingsphere动态数据源
- navicat 导出数据库的表结构
猜你喜欢

Pytoch configuration

FileZilla Client下載安裝
![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

渤、黄海的潮汐特征

Nce detail of softmax approximation

Vs 2019 installation and configuration opencv

The idea cannot be loaded, and the market solution can be applied (pro test)

为什么线程崩溃不会导致 JVM 崩溃

Ffmpeg one / more pictures synthetic video

Lvgl usage experience
随机推荐
VS 2019安装及配置opencv
[mathematical logic] propositional logic (propositional and connective review | propositional formula | connective priority | truth table satisfiable contradiction tautology)
简易版 微信小程序开发之页面跳转、数据绑定、获取用户信息、获取用户位置信息
Applet (continuous update)
@Accessors注解作用指定前缀遵守驼峰命名
Using jasmine to monitor constructors - spying on a constructor using Jasmine
递归:一维链表和数组
Summary of electromagnetic spectrum
Limit of one question per day
Nanning water leakage detection: warmly congratulate Guangxi Zhongshui on winning the first famous brand in Guangxi
Latest version of NPM: the "NPM" item cannot be recognized as the name of a cmdlet, function, script file, or runnable program. Please check
900w+ data, from 17s to 300ms, how to operate
Numpy warning visibledeprecationwarning: creating an ndarray from ragged needed sequences
ffmpeg录制屏幕和截屏
Pytorch multi card distributed training distributeddataparallel usage
解决高並發下System.currentTimeMillis卡頓
The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
VS 2019 配置tensorRT生成engine
Introduction à mongodb
MySQL practice 45 lecture [transaction isolation]