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

边栏推荐
- 查看zabbix-release-5.0-1.el8.noarch.rpm包内容
- 牛客网刷题训练(四)
- ros2知识:在单个进程中布置多个节点
- typescript10-commonly used basic types
- MySQL database constraints, table design
- Jmeter参数传递方式(token传递,接口关联等)
- 图像处理工具设计
- How to Add a Navigation Menu on Your WordPress Site
- typescript15- (specify both parameter and return value types)
- typescript11 - data types
猜你喜欢
随机推荐
typescript17-函数可选参数
MySQL master-slave replication and read-write separation script - pro test available
SereTOD2022 Track2代码剖析-面向半监督和强化学习的任务型对话系统挑战赛
WMware Tools安装失败segmentation fault解决方法
Problem record in the use of TypeScript
Bypass of xss
MySql data recovery method personal summary
GO GOPROXY proxy Settings
MySQL系列一:账号管理与引擎
ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!
typescript10-常用基础类型
xss bypass: prompt(1)
24. Please talk about the advantages and disadvantages of the singleton pattern, precautions, usage scenarios
Consistency and Consensus of Distributed Systems (1) - Overview
BOM系列之Navigator对象
(5) fastai application
typescript15-(同时指定参数和返回值类型)
Niuke.com question brushing training (4)
【愚公系列】2022年07月 Go教学课程 015-运算符之赋值运算符和关系运算符
Error occurred while trying to proxy request项目突然起不来了
![[In-depth and easy-to-follow FPGA learning 13---------Test case design 1]](/img/1c/a88ba3b01d2e2302c26ed5f730b956.png)








