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

边栏推荐
猜你喜欢

tensorflow与GPU版本对应安装问题

How to Add a Navigation Menu on Your WordPress Site

【网络安全】文件上传靶场通关(1-11关)

typescript10-commonly used basic types

Installation problem corresponding to tensorflow and GPU version

297. 二叉树的序列化与反序列化

射频器件的基本参数1

Unity2D horizontal version game tutorial 4 - item collection and physical materials

基于Keras_bert模型的Bert使用与字词预测

Mysql:Invalid default value for TIMESTAMP
随机推荐
权限管理怎么做的?
分布式.分布式锁
ShardingSphere之水平分库实战(四)
解析云原生消息流系统 Apache Pulsar 能力及场景
typescript16-void
Jmeter参数传递方式(token传递,接口关联等)
Installation problem corresponding to tensorflow and GPU version
DOM系列之动画函数封装
使用docker安装mysql
822. Walk the Grid
ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!
射频器件的基本参数1
[Tang Yudi Deep Learning-3D Point Cloud Combat Series] Study Notes
Preparations for web vulnerabilities
MySql data recovery method personal summary
金融政企被攻击为什么要用高防CDN?
【Yugong Series】July 2022 Go Teaching Course 019-For Circular Structure
分布式系统的一致性与共识(1)-综述
unity2D横版游戏教程4-物品收集以及物理材质
Why use high-defense CDN when financial, government and enterprises are attacked?