当前位置:网站首页>[牛客网刷题 Day4] JZ55 二叉树的深度
[牛客网刷题 Day4] JZ55 二叉树的深度
2022-07-05 08:39:00 【strawberry47】
题目:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度,根节点的深度视为 1 。
思路:
第一次遇到树的题目,有一点点懵逼,不太懂他的构建过程
第一反应是用递归,因为结束的条件很容易想到嘛:左节点右节点都为空
but,我不知道应该怎么移动根节点耶。。。
答案:
看了答案,也用到了递归的思想:
有点懵。。递归好难啊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
还可以用到队列的思想:
import queue
class Solution:
def maxDepth(self , root: TreeNode) -> int:
# 空节点没有深度
if not root:
return 0
# 队列维护层次后续节点
q= queue.Queue()
# 根入队
q.put(root)
# 记录深度
res = 0
# 层次遍历
while not q.empty():
# 记录当前层有多少节点
n = q.qsize()
# 遍历完这一层,再进入下一层
for i in range(n):
node = q.get()
# 添加下一层的左右节点
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
# 深度加1
res += 1
return res
队列的思路容易理解一些,就是将每一层都存进去,看看能存多少层,就加一
边栏推荐
- Guess riddles (2)
- Agile project management of project management
- Count the number of inputs (C language)
- leetcode - 445. Add two numbers II
- 【三层架构及JDBC总结】
- Warning: retrying occurs during PIP installation
- MATLAB小技巧(28)模糊綜合評價
- Matlab tips (28) fuzzy comprehensive evaluation
- [formation quotidienne - Tencent Selection 50] 557. Inverser le mot III dans la chaîne
- 剑指 Offer 09. 用两个栈实现队列
猜你喜欢
随机推荐
猜谜语啦(4)
STM32 single chip microcomputer -- volatile keyword
MySQL之MHA高可用集群
How to write cover letter?
Keil use details -- magic wand
696. Count binary substring
第十八章 使用工作队列管理器(一)
Lori remote control LEGO motor
UE像素流,来颗“减肥药”吧!
Search data in geo database
99 multiplication table (C language)
2020-05-21
319. Bulb switch
实例008:九九乘法表
STM32 single chip microcomputer - external interrupt
Count the number of inputs (C language)
Arrangement of some library files
2022.7.4-----leetcode. one thousand and two hundred
Business modeling | process of software model
[three tier architecture and JDBC summary]