当前位置:网站首页>[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
边栏推荐
猜你喜欢
EA introduction notes
Example 006: Fibonacci series
[matlab] matlab reads and writes Excel
Lori remote control LEGO motor
[牛客网刷题 Day4] JZ35 复杂链表的复制
leetcode - 445. Add two numbers II
Business modeling of software model | vision
How to write cover letter?
Redis implements a high-performance full-text search engine -- redisearch
Guess riddles (6)
随机推荐
One dimensional vector transpose point multiplication np dot
Sword finger offer 06 Print linked list from end to end
Business modeling of software model | overview
Run菜单解析
Classification of plastic surgery: short in long long long
Guess riddles (4)
leetcode - 445. Add two numbers II
Bit operation related operations
287. 寻找重复数-快慢指针
asp.net(c#)的货币格式化
猜谜语啦(6)
[three tier architecture]
Numpy pit: after the addition of dimension (n, 1) and dimension (n,) array, the dimension becomes (n, n)
ECMAScript6介绍及环境搭建
Arrangement of some library files
C语言标准函数scanf不安全的原因
Xrosstools tool installation for X-Series
Search data in geo database
图解八道经典指针笔试题
EA introduction notes