当前位置:网站首页>[牛客网刷题 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
队列的思路容易理解一些,就是将每一层都存进去,看看能存多少层,就加一
边栏推荐
- 猜谜语啦(2)
- STM32 --- NVIC interrupt
- Chapter 18 using work queue manager (1)
- 每日一题——输入一个日期,输出它是该年的第几天
- 287. Looking for repeats - fast and slow pointer
- 關於線性穩壓器的五個設計細節
- Matlab tips (28) fuzzy comprehensive evaluation
- Sword finger offer 06 Print linked list from end to end
- 实例007:copy 将一个列表的数据复制到另一个列表中。
- Tips 1: Web video playback code
猜你喜欢
随机推荐
Esp8266 interrupt configuration
Xrosstools tool installation for X-Series
【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
287. 寻找重复数-快慢指针
Business modeling of software model | object modeling
Run menu analysis
暑假第一周
Detailed summary of FIO test hard disk performance parameters and examples (with source code)
Example 007: copy data from one list to another list.
STM32---IIC
Arrangement of some library files
猜谜语啦(10)
696. Count binary substring
Typescript hands-on tutorial, easy to understand
整形的分类:short in long longlong
Five design details of linear regulator
C language data type replacement
Example 008: 99 multiplication table
Array integration initialization (C language)
实例004:这天第几天 输入某年某月某日,判断这一天是这一年的第几天?








