当前位置:网站首页>Xiaohei's leetcode journey: 104. The maximum depth of a binary tree
Xiaohei's leetcode journey: 104. The maximum depth of a binary tree
2022-07-31 00:59:00 【little black invincible】
Little black solution one:深度优先
# 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)
Little black solution 2:宽度优先
# 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:
# The number of nodes in the queue
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
边栏推荐
- ELK deployment script---pro test available
- typescript15-(同时指定参数和返回值类型)
- MySQL Series 1: Account Management and Engine
- 【Yugong Series】July 2022 Go Teaching Course 013-Constants, Pointers
- 人工智能与云安全
- 金融政企被攻击为什么要用高防CDN?
- BOM系列之Navigator对象
- Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
- BOM系列之history对象
- 822. Walk the Grid
猜你喜欢
随机推荐
【952. Calculate the maximum component size according to the common factor】
场景之多数据源查询及数据下载问题
Zabbix干啥用?
《实战》基于情感词典的文本情感分析与LDA主题分析
查看zabbix-release-5.0-1.el8.noarch.rpm包内容
Installation problem corresponding to tensorflow and GPU version
Image processing tool design
24. 请你谈谈单例模式的优缺点,注意事项,使用场景
【Yugong Series】July 2022 Go Teaching Course 019-For Circular Structure
不用Swagger,那我用啥?
35. 反转链表
Jetpack Compose learning (8) - State and remeber
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
Adding, deleting, modifying and checking the foundation of MySQL
xss bypass: prompt(1)
In Google Cloud API gateway APISIX T2A and T2D performance test
ShardingSphere之水平分库实战(四)
API 网关 APISIX 在Google Cloud T2A 和 T2D 的性能测试
TypeScript在使用中出现的问题记录
埃拉托斯特尼筛法