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

边栏推荐
猜你喜欢

Kotlin协程:协程上下文与上下文元素

Can deep learning solve the parameters of a specific function?

go mode tidy出现报错go warning “all“ matched no packages

The client series of the DOM series

不用Swagger,那我用啥?

Jmeter parameter transfer method (token transfer, interface association, etc.)

C language force buckles the rotating image of the 48th question.auxiliary array

typescript17 - function optional parameters

Error in go mode tidy go warning “all” matched no packages

华为“天才少年”稚晖君又出新作,从零开始造“客制化”智能键盘
随机推荐
Go study notes (84) - Go project directory structure
Kotlin协程:协程上下文与上下文元素
The client series of the DOM series
MySql data recovery method personal summary
ShardingSphere之垂直分库分表实战(五)
C语言力扣第48题之旋转图像。辅助数组
Go 学习笔记(84)— Go 项目目录结构
ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!
DOM系列之scroll系列
【952. Calculate the maximum component size according to the common factor】
Sping.事务的传播特性
ECCV 2022丨轻量级模型架构火了,力压苹果MobileViT(附代码和论文下载)
Rocky/GNU之Zabbix部署(1)
【Multithreading】
ShardingSphere's unsharded table configuration combat (6)
ShardingSphere之公共表实战(七)
【Yugong Series】July 2022 Go Teaching Course 017-IF of Branch Structure
typescript16-void
(5) fastai application
Error ER_NOT_SUPPORTED_AUTH_MODE Client does not support authentication protocol requested by serv