当前位置:网站首页>小黑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

边栏推荐
- Error occurred while trying to proxy request The project suddenly can't get up
- 【愚公系列】2022年07月 Go教学课程 017-分支结构之IF
- ShardingSphere之垂直分库分表实战(五)
- How to Add a Navigation Menu on Your WordPress Site
- Zabbix干啥用?
- Go study notes (84) - Go project directory structure
- typescript13-类型别名
- ros2知识:在单个进程中布置多个节点
- WEB安全基础 - - -漏洞扫描器
- 【愚公系列】2022年07月 Go教学课程 016-运算符之逻辑运算符和其他运算符
猜你喜欢

MySQL高级-六索引优化

Typescript18 - object type

MySQL数据库面试题总结(2022最新版)

Rocky/GNU之Zabbix部署(3)

Yolov7实战,实现网页端的实时目标检测

API 网关 APISIX 在Google Cloud T2A 和 T2D 的性能测试

Mini Program - Global Data Sharing
![[Tang Yudi Deep Learning-3D Point Cloud Combat Series] Study Notes](/img/52/88ad349eca136048acd0f328d4f33c.png)
[Tang Yudi Deep Learning-3D Point Cloud Combat Series] Study Notes

Summary of MySQL database interview questions (2022 latest version)

ShardingSphere's unsharded table configuration combat (6)
随机推荐
分布式.分布式锁
ShardingSphere之读写分离(八)
Gabor filter study notes
WEB Security Basics - - - Vulnerability Scanner
Go 学习笔记(84)— Go 项目目录结构
Jetpack Compose learning (8) - State and remeber
The client series of the DOM series
typescript12-联合类型
MySQL notes under
Common network status codes
【多线程】
C language force buckles the rotating image of the 48th question.auxiliary array
【愚公系列】2022年07月 Go教学课程 015-运算符之赋值运算符和关系运算符
24. 请你谈谈单例模式的优缺点,注意事项,使用场景
ShardingSphere's public table combat (7)
程序员工作三年攒多少钱合适?
ABC 261 F - Sorting Color Balls (reverse pair)
Niuke.com question brushing training (4)
Can deep learning solve the parameters of a specific function?
What is Promise?What is the principle of Promise?How to use Promises?