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

边栏推荐
猜你喜欢

DOM系列之 client 系列

Typescript18 - object type

typescript13-类型别名

【ABAP】MFBF过账到质量检验库存类型Demo

网站频繁出现mysql等数据库连接失败等信息解决办法

C语言力扣第48题之旋转图像。辅助数组

Can deep learning solve the parameters of a specific function?
![[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

ShardingSphere's vertical sub-database sub-table actual combat (5)

Kotlin协程:协程上下文与上下文元素
随机推荐
[In-depth and easy-to-follow FPGA learning 13---------Test case design 1]
Error occurred while trying to proxy request The project suddenly can't get up
查看zabbix-release-5.0-1.el8.noarch.rpm包内容
Jmeter parameter transfer method (token transfer, interface association, etc.)
Typescript14 - (type) of the specified parameters and return values alone
深度学习可以求解特定函数的参数么?
Can deep learning solve the parameters of a specific function?
Problem record in the use of TypeScript
Responsive layout vs px/em/rem
C language force buckles the rotating image of the 48th question.auxiliary array
Consistency and Consensus of Distributed Systems (1) - Overview
Meeting OA project pending meeting, all meeting functions
typescript9-常用基础类型
XSS related knowledge
MySQL database constraints, table design
MySQL triggers
ELK deployment script---pro test available
分布式.分布式锁
Rocky/GNU之Zabbix部署(3)
【Demo】ABAP Base64加解密测试