当前位置:网站首页>Sword finger offer 55 - I. depth of binary tree
Sword finger offer 55 - I. depth of binary tree
2022-07-29 00:10:00 【The harder you work, the luckier you are】
The traversal methods of trees are generally divided into two categories : Depth-first search (DFS)、 Breadth first search (BFS);
common DFS : The first sequence traversal 、 In the sequence traversal 、 After the sequence traversal ;
common BFS : Sequence traversal ( That is, traverse by layer ).
Depth first search of trees often uses recursive or Stack Realization , This article uses recursion to realize .
Method 1 : The first sequence traversal (DFS)
Termination conditions : Compare the final results when leaf nodes res And the depth of this road
Recursive parameter : Current node node, Depth of current road k
Recursive work : Traverse the left and right child nodes of the current node
class Solution:
def maxDepth(self, root):
def dfs(node,k):
if not node:
if self.res<k:
self.res=k
return
else:
return
k+=1
dfs(node.left,k)
dfs(node.right,k)
self.res=float("-inf")
dfs(root,0)
return self.res
To find the depth of the tree, you need to traverse all nodes of the tree , The following will introduce based on After the sequence traversal (DFS) and Sequence traversal (BFS) There are two solutions to this problem .
Method 2 : After the sequence traversal ( Left and right )(DFS)
Key points : The depth of this tree and its left ( Right ) The relationship between the depth of the subtree . obviously , The depth of this tree be equal to The depth of the left subtree And Depth of right subtree Medium Maximum +1.
Termination conditions : When root It's empty , Indicates that the leaf node... Has been crossed , Therefore return depth 0 .
Recursive work : In essence, it is a post order traversal of the tree .
Computing node root Of The depth of the left subtree , That is to call maxDepth(root.left);
Computing node root Of Depth of right subtree , That is to call maxDepth(root.right);
Return value : return The depth of this tree , namely max(maxDepth(root.left), maxDepth(root.right)) + 1.
class Solution:
def maxDepth(self, root):
def dfs(node):
if not node:return 0
return max(dfs(node.left),dfs(node.right))+1
return dfs(root) Method 3 : Sequence traversal (BFS)
Sequence traversal of trees / Breadth first search often uses queue Realization .
Key points : Every layer , Then the counter +1 , Until the traversal is complete , Then you can get the depth of the tree .
Algorithm analysis :
Special case handling : When root It's empty , Go straight back to depth 0 .
initialization : queue queue ( Add the root node root ), Counter res = 0.
Loop traversal : When queue Jump out when empty .
Initialize an empty list tmp , It is used to temporarily store the nodes of the next layer ;
Traverse the queue : Traverse queue The nodes in node , And add its left child node and right child node tmp;
Update queue : perform queue = tmp , Assign the next level node to queue;
Count the number of floors : perform res += 1 , Represents the number of layers plus 1;
Return value : return res that will do .
Implement queue with list
class Solution:
def maxDepth(self, root):
if not root:return 0
queue=[root]
res=0
while queue:
tmp = []
for node in queue:
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
queue=tmp
res+=1
return resUse a two-way queue
import collections
class Solution:
def maxDepth(self, root):
if not root:return 0# Note that the depth of the tree is empty
queue=collections.deque()
queue.append(root)
res=0
while queue:
tmp=collections.deque()
while queue:
node=queue.popleft()
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
queue=tmp
res+=1
return res边栏推荐
- NAT如何配置地址转换
- Dual for loop optimization
- PHP poster QR code synthesis
- Cmake basic learning
- EN 1873屋面用装配附件.塑料单个屋面灯—CE认证
- JS four formulas for judging data types
- DevOps在物联网解决方案中的应用
- Android studio连接MySQL并完成简单的登录注册功能
- Leetcode59. Spiral matrix II
- 【C】 Replace spaces and realize binary parity bit exchange of integers by macros
猜你喜欢

Application of Devops in Internet of things solutions

ISO 13400(DoIP)标准解读

Doip communication of canoe application case

Leetcode60. permutation sequence

Leetcode62. Different paths

Develop effective Tao spell

Leetcode61. rotating linked list

SAP temporary tablespace error handling

Interpretation of ISO 13400 (doip) standard

【C】 Introduction and Simulation Implementation of ATOI and offsetof
随机推荐
laptop外接显示器
[detailed and super simple] how to use websocket links
Eye of depth (18) -- partial derivative
Genomic DNA isolation Worthington ribonuclease A
Doip communication of canoe application case
What do you need to bring with you for the NPDP exam? Stationery carrying instructions
1-8 basic use of props
Develop effective Tao spell
Leetcode60. permutation sequence
Powercli batch add esxi to vCenter
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
Web系统常见安全漏洞介绍及解决方案-CSRF攻击
【MySQL系列】MySQL数据库基础
How NAT configures address translation
[TA frost wolf _may- "hundred people plan"] art 2.2 model basis
Real time data warehouse: Didi's real-time data warehouse landing practice
GhostNets on Heterogeneous Devices via Cheap Operations
Control fillet stroke materialshapedrawable
NPM replace the latest Taobao image
Leetcode63. 不同路径 II
https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof/