力扣Hot100–104.二叉树的最大深度
要求:给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
明确概念:
1、二叉树的 高度 是指任意节点到叶子节点的距离(从下到上,用后序遍历)
2、二叉树的 深度 是指任意节点到根节点的距离(从上到下,用前序遍历)
3、后序遍历得到的 根节点的高度 就是该二叉树的 最大深度
后序遍历解法:
递归,左右中
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def getheight(node):
if node is None:
return 0
lefthight =getheight(node.left)
rightheight = getheight(node.right)
height = 1+max(lefthight,rightheight)
return height
result=getheight(root)
return result
# 精简解法
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def getheight(node):
if node is None:
return 0
return 1+max(getheight(node.left),getheight(node.right))
result=getheight(root)
return result
层序遍历解法:
一层一层找下去,比较好理解
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
result=0
queue = deque()
if root:
queue.append(root)
else:
return 0
while queue:
result += 1 # 直接在这里计数
size = len(queue)
for _ in range(size):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result

510

被折叠的 条评论
为什么被折叠?



