当前位置:网站首页>[牛客网刷题 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
队列的思路容易理解一些,就是将每一层都存进去,看看能存多少层,就加一
边栏推荐
- U8g2 drawing
- C语言标准函数scanf不安全的原因
- Stm32--- systick timer
- Typescript hands-on tutorial, easy to understand
- Example 008: 99 multiplication table
- Illustration of eight classic pointer written test questions
- Arrangement of some library files
- 【日常训练】1200. 最小绝对差
- Bluebridge cup internet of things competition basic graphic tutorial - clock selection
- Example 004: for the day of the day, enter a day of a month of a year to judge the day of the year?
猜你喜欢

【三层架构】

STM32 single chip microcomputer -- debug in keil5 cannot enter the main function

Guess riddles (5)

猜谜语啦(8)

Detailed summary of FIO test hard disk performance parameters and examples (with source code)

每日一题——输入一个日期,输出它是该年的第几天
实例001:数字组合 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

猜谜语啦(3)

猜谜语啦(7)

EA introduction notes
随机推荐
【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
Apaas platform of TOP10 abroad
Guess riddles (9)
Tips 1: Web video playback code
实例010:给人看的时间
MySQL MHA high availability cluster
Digital analog 2: integer programming
[noi simulation] juice tree (tree DP)
实例001:数字组合 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
STM32 single chip microcomputer -- volatile keyword
Illustration of eight classic pointer written test questions
Pytorch entry record
Is the security account given by Yixue school safe? Where can I open an account
STM32 summary (HAL Library) - DHT11 temperature sensor (intelligent safety assisted driving system)
剑指 Offer 09. 用两个栈实现队列
Guess riddles (2)
猜谜语啦(3)
The first week of summer vacation
猜谜语啦(2)
An enterprise information integration system