当前位置:网站首页>[牛客网刷题 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
队列的思路容易理解一些,就是将每一层都存进去,看看能存多少层,就加一
边栏推荐
猜你喜欢
[NAS1](2021CVPR)AttentiveNAS: Improving Neural Architecture Search via Attentive Sampling (未完)
Count the number of inputs (C language)
整形的分类:short in long longlong
实例010:给人看的时间
Array integration initialization (C language)
Arduino operation stm32
猜谜语啦(142)
Old Wang's esp8266 and old Wu's ws2818 light strip
Apaas platform of TOP10 abroad
Numpy pit: after the addition of dimension (n, 1) and dimension (n,) array, the dimension becomes (n, n)
随机推荐
第十八章 使用工作队列管理器(一)
【日常训练--腾讯精选50】557. 反转字符串中的单词 III
Bluebridge cup internet of things basic graphic tutorial - GPIO output control LD5 on and off
Reasons for the insecurity of C language standard function scanf
[daily training] 1200 Minimum absolute difference
Guess riddles (4)
Digital analog 1: linear programming
猜谜语啦(8)
Daily question - input a date and output the day of the year
STM32 single chip microcomputer -- debug in keil5 cannot enter the main function
Pytorch entry record
Business modeling of software model | vision
Detailed summary of FIO test hard disk performance parameters and examples (with source code)
287. 寻找重复数-快慢指针
Array integration initialization (C language)
2020-05-21
STM32---ADC
Bluebridge cup internet of things basic graphic tutorial - GPIO input key control LD5 on and off
99 multiplication table (C language)
leetcode - 445. 两数相加 II