当前位置:网站首页>小黑leetcode之旅:104. 二叉树的最大深度
小黑leetcode之旅:104. 二叉树的最大深度
2022-07-31 00:52:00 【小黑无敌】
小黑解法一:深度优先
# Definition for a binary tree node.
# 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
def getDepth(node):
if node:
return max(getDepth(node.left),getDepth(node.right)) + 1
else:
return 0
return getDepth(root)
小黑解法二:宽度优先
# Definition for a binary tree node.
# 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
q = collections.deque([root])
depth = 0
while q:
# 队列中结点的个数
n = len(q)
for i in range(n):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
depth += 1
return depth
边栏推荐
- go mode tidy出现报错go warning “all“ matched no packages
- Kotlin协程:协程上下文与上下文元素
- 人工智能与云安全
- [Yugong Series] July 2022 Go Teaching Course 016-Logical Operators and Other Operators of Operators
- mysql索引失效的常见9种原因详解
- MySQL Series 1: Account Management and Engine
- 图像处理工具设计
- Typescript18 - object type
- MySql数据恢复方法个人总结
- 响应式布局与px/em/rem的比对
猜你喜欢
随机推荐
TypeScript在使用中出现的问题记录
Rocky/GNU之Zabbix部署(3)
分布式.分布式锁
WMware Tools安装失败segmentation fault解决方法
MySQL笔记下
GO GOPROXY代理设置
Rocky/GNU之Zabbix部署(1)
埃拉托斯特尼筛法
IOT cross-platform component design scheme
ECCV 2022丨轻量级模型架构火了,力压苹果MobileViT(附代码和论文下载)
MySQL database constraints, table design
WEB安全基础 - - -漏洞扫描器
The level of ShardingSphere depots in actual combat (4)
Artificial Intelligence and Cloud Security
typescript14-(单独指定参数和返回值的类型)
unity2D横版游戏教程4-物品收集以及物理材质
Error ER_NOT_SUPPORTED_AUTH_MODE Client does not support authentication protocol requested by serv
typescript15-(同时指定参数和返回值类型)
typescript13 - type aliases
Can deep learning solve the parameters of a specific function?