当前位置:网站首页>LeetCode #104.二叉树的最大深度
LeetCode #104.二叉树的最大深度
2022-08-08 19:11:00 【张楚明ZCM】
题目截图

方法一:深度优先搜索(递归)
将二叉树不断分解,直到左子树和右子树的最大深度即可知道二叉树的最大深度。
每个字数又可以不断分解成新的字数,直到没有结点,每一次分解,加一层。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root :
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1复杂度分析
时间复杂度:
其中
为二叉树节点的个数。每个节点在递归中只被遍历一次。
空间复杂度:
其中
表示二叉树的高度。
完整测试代码
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root :
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
class main:
a = Solution()
node1 = TreeNode(3)
node2 = TreeNode(9)
node3 = TreeNode(20)
node4 = TreeNode(15)
node5 = TreeNode(7)
node1.left = node2
node1.right = node3
node3.left = node4
node3.right = node5
b = a.maxDepth(node1)
print(b)
if __name__ == '__main__':
main()方法二:广度优先搜索
利用队列保存每一层的所有结点,把队列里的所有结点出队列,然后把出队列的结点的子节点加入队列。
如例题中的二叉树

刚开始,深度为0。
先加入第一层的3,然后第一层的3出队列,第一层所有结点出队列,深度+1。
加入第二层的9和20,然后9出队列,由于9没有子节点,不添加新的结点进入队列。
再让20出队列,此时第二层所有结点已经出队列,深度+1。
加入第三层的15和7。
再分别让15和7出队列,由于没有子节点,不添加任何新节点,此时所有结点出队列,队列为空,深度+1。
最终返回深度,深度为3。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root == None:
return 0
queue = [root]
depth = 0
while queue:
n = len(queue)
for i in range(n):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
depth += 1
return depth复杂度分析
时间复杂度:
空间复杂度:
边栏推荐
猜你喜欢

The history of cartoon rendering

什么是Shell?从小白到入门你只差一个它

数字化工厂建设的内容主要有哪三个方面

Fortinet new cloud native protection products launched amazon cloud platform of science and technology

数据泵导出数据报39006是什么原因

WPF DataGrid 展示数据

电脑win键没有反应(最全方案)

MogDB study notes - starting from 0
The difference between Redis' memory elimination strategy and expired deletion strategy

16. Learn Lua file I/O together
随机推荐
如何在Firewalld中为特定IP地址开放端口
JVM调优-JVM调优实践一
在Unity URP中实现Forward+
PX4-做飞控二次开发需要知道的事情-Cxm
Rethinking HTAP database caused by rereading GPDB and TiDB papers
PyTorch入门:(二)Tensorboard的使用
数据库学习之库的操作
shell的各种三角形
Dry goods: design high concurrency architecture from scratch
hdu2018 母牛的故事(模拟)
Ability in general, but it can be large horizontal jump freely?Where is the better?
如何在EasyDSS中使用ffmpeg实现点播视频的拼接与合成?
启牛商学院开户是安全的吗?开户靠谱吗?
室外光纤资源管理——可视化管理平台
生成验证码工具类
Oracle - table
5次折戟IPO,互联网家装这条路,没土巴兔想的那么简单
【761. Special binary sequence】
nyoj 712 Exploring treasure
Which company is the best for futures account opening? It must be formal and safe