当前位置:网站首页>[Niuke brush questions day4] jz55 depth of binary tree
[Niuke brush questions day4] jz55 depth of binary tree
2022-07-05 08:43:00 【strawberry47】
subject :
Enter a binary tree , Find the depth of the tree . The nodes that pass from the root node to the leaf node ( Containing root 、 leaf ) A path to a tree , The length of the longest path is the depth of the tree , The depth of the root node is treated as 1 .
Ideas :
First encounter the problem of trees , A little confused , I don't understand his construction process
The first reaction is to use recursion , Because the end condition is easy to think of : Both left and right nodes are empty
but, I don't know how to move the root node ...
answer :
Looking at the answer , The idea of recursion is also used :
mentally .. Recursion is so hard o(╥﹏╥)o
class Solution:
def TreeDepth(self , pRoot: TreeNode) -> int:
# write code here
if not pRoot:
return 0
left = right =0
if pRoot.left:
left = self.TreeDepth(pRoot.left)
if pRoot.right:
right = self.TreeDepth(pRoot.right)
return max([left,right])+1
You can also use the idea of queues :
import queue
class Solution:
def maxDepth(self , root: TreeNode) -> int:
# Empty nodes have no depth
if not root:
return 0
# Subsequent nodes of the queue maintenance hierarchy
q= queue.Queue()
# Root in the team
q.put(root)
# Record the depth
res = 0
# Level traversal
while not q.empty():
# Record how many nodes there are in the current layer
n = q.qsize()
# Traverse this layer , Go on to the next floor
for i in range(n):
node = q.get()
# Add the left and right nodes of the next layer
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
# Depth plus 1
res += 1
return res
The idea of queue is easier to understand , Is to save every layer , See how many layers you can save , Plus one
边栏推荐
猜你喜欢
UE pixel stream, come to a "diet pill"!
An enterprise information integration system
资源变现小程序添加折扣充值和折扣影票插件
Example 009: pause output for one second
Guess riddles (11)
Guess riddles (2)
MATLAB小技巧(28)模糊综合评价
STM32 lights up the 1.8-inch screen under Arduino IDE
Arduino operation stm32
Numpy pit: after the addition of dimension (n, 1) and dimension (n,) array, the dimension becomes (n, n)
随机推荐
Esp8266 interrupt configuration
我从技术到产品经理的几点体会
GEO数据库中搜索数据
287. 寻找重复数-快慢指针
第十八章 使用工作队列管理器(一)
Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
Cmder of win artifact
Guess riddles (5)
Halcon clolor_ pieces. Hedv: classifier_ Color recognition
Some pitfalls of win10 network sharing
asp.net(c#)的货币格式化
Bit operation related operations
Daily question - input a date and output the day of the year
Sword finger offer 06 Print linked list from end to end
猜谜语啦(7)
Task failed task_ 1641530057069_ 0002_ m_ 000000
Matlab tips (28) fuzzy comprehensive evaluation
Dynamic dimensions required for input: input, but no shapes were provided. Automatically overriding
U8g2 drawing
Meta标签详解