当前位置:网站首页>小黑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
边栏推荐
- background has no effect on child elements of float
- Oracle has a weird temporary table space shortage problem
- Rocky/GNU之Zabbix部署(2)
- typescript9 - common base types
- A complete guide to avoiding pitfalls for the time-date type "yyyy-MM-dd HHmmss" in ES
- 【愚公系列】2022年07月 Go教学课程 019-循环结构之for
- MySql数据恢复方法个人总结
- Image processing tool design
- 华为“天才少年”稚晖君又出新作,从零开始造“客制化”智能键盘
- 一万了解 Gateway 知识点
猜你喜欢
Meeting OA project pending meeting, all meeting functions
How to Add a Navigation Menu on Your WordPress Site
分布式.幂等性
Jmeter parameter transfer method (token transfer, interface association, etc.)
API 网关 APISIX 在Google Cloud T2A 和 T2D 的性能测试
Typescript18 - object type
Rocky/GNU之Zabbix部署(2)
Mysql systemized JOIN operation example analysis
Error occurred while trying to proxy request项目突然起不来了
【952. Calculate the maximum component size according to the common factor】
随机推荐
程序员工作三年攒多少钱合适?
Summary of MySQL database interview questions (2022 latest version)
牛客网刷题训练(四)
background has no effect on child elements of float
SereTOD2022 Track2代码剖析-面向半监督和强化学习的任务型对话系统挑战赛
[Yugong Series] July 2022 Go Teaching Course 016-Logical Operators and Other Operators of Operators
ShardingSphere之未分片表配置实战(六)
typescript9 - common base types
typescript15- (specify both parameter and return value types)
Common network status codes
ros2知识:在单个进程中布置多个节点
ShardingSphere's unsharded table configuration combat (6)
Mini Program - Global Data Sharing
BOM系列之Navigator对象
BOM系列之history对象
Meeting OA project pending meeting, all meeting functions
MySQL高级-六索引优化
typescript12 - union types
unity2D横版游戏教程4-物品收集以及物理材质
ELK deployment script---pro test available