当前位置:网站首页>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边栏推荐
- 【MySQL 8】Generated Invisible Primary Keys(GIPK)
- Everything you have learned will come in handy at some point in your life (turn)
- Leetcode61. 旋转链表
- Real time data warehouse: Didi's real-time data warehouse landing practice
- Doip communication of canoe application case
- NAT如何配置地址转换
- GhostNets on Heterogeneous Devices via Cheap Operations
- Leetcode62. Different paths
- JS four formulas for judging data types
- 1-4 类的复习
猜你喜欢

EN 1873 assembly accessories for roofing - plastic single roof lamps - CE certification

熊市下PLATO如何通过Elephant Swap,获得溢价收益?

器利而工善,以RPA+LCAP赋能企业司库管理数字化升级

Doip communication of canoe application case

Eight performance analysis indicators of effective supply chain management (Part 1)

Detailed explanation of 9 common reasons for MySQL index failure

Uricase - Characteristics of uricase in Worthington pig liver:

JS advanced ES6 ~ es13 new features

EN 1935 building hardware. Single axis hinge - CE certification

Worthington - chemical properties and related studies of Worthington trypsin
随机推荐
PHP poster QR code synthesis
Yolov5 learning notes (I) -- principle overview
EN 12101-8:2011烟雾和热量控制系统防烟挡板—CE认证
Real time data warehouse: meituan's implementation of real-time data warehouse construction based on Flink
Leetcode64. Minimum path sum
VirtualLab基础实验教程-8.傅里叶变换(1)
After SAP Oracle replicates a new instance, the remote connection of the database reports an error ora-01031
Application of Devops in Internet of things solutions
Hutool official website (is hutool easy to use)
Leetcode62. 不同路径
熊市下PLATO如何通过Elephant Swap,获得溢价收益?
[detailed and super simple] how to use websocket links
curl (7) Failed connect to localhost8080; Connection refused
Oracle创建表空间和用户
ISO 13400(DoIP)标准解读
Powercli VMware vCenter deploys conventional new VMS in batch through self built PXE server with one click
With the help of rpa+lcap, the enterprise treasurer management can be upgraded digitally
[TA frost wolf _may- "hundred people plan"] art 2.2 model basis
SAP temporary tablespace error handling
VS2005 accesses the setting method "recommended collection" of vss2005 through sourceoffsite
https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof/