2025/09/07 LeetCode 104.二叉树的最大深度
解法1:迭代法,使用层序遍历
# 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 queue = collections.deque([root]) depth = 0 while queue: for _ in range(len(queue)): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) depth += 1 return depth
解法2:递归法
写法(1)精简代码
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
知识点:
(1)二叉树节点的高度和深度概念
- 二叉树节点的深度(从上往下):指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度(从下往上):指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
根节点的高度就是二叉树的最大深度,所以本题中可以通过后序求的根节点高度来求二叉树最大深度。
写法2:后序遍历递归
class Solution: def maxDepth(self, root: TreeNode) -> int: return self.getDepth(root) def getDepth(self, node): if not node: return 0 leftheight = self.getDepth(node.left) #左 rightheight = self.getDepth(node.right) #右 height = 1 + max(leftheight, rightheight) #中 return height
写法3:前序遍历递归
class Solution: def maxDepth(self, root: TreeNode) -> int: self.result = 0 if not root: return self.result self.getDepth(root, 1) return self.result def getDepth(self, node, depth): self.result = max(self.result, depth) if not node.left and not node.right: return if node.left: self.getDepth(node.left, depth+1) if node.right: self.getDepth(node.right, depth+1) return
解法1:迭代法
写法(1)使用层序遍历,队列数据结构
""" # Definition for a Node. class Node: def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 queue = collections.deque([root]) depth = 0 while queue: for _ in range(len(queue)): node = queue.popleft() for child in node.children: queue.append(child) depth += 1 return depth
写法(2)使用栈数据结构
class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 max_depth = 0 st = [(root, 1)] while st: node, depth = st.pop() max_depth = max(max_depth, depth) for child in node.children: st.append((child, depth + 1)) return max_depth
解法2:递归法
写法(1)精简代码,是后序遍历递归的精简写法
class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 if not root.children: return 1 return 1 + max(self.maxDepth(child) for child in root.children)
写法(2)前序遍历递归
class Solution: def maxDepth(self, root: 'Node') -> int: self.result = 0 if not root: return self.result self.getDepth(root, 1) return self.result def getDepth(self, node, depth): self.result = max(self.result, depth) if not node.children: return for child in node.children: self.getDepth(child, depth+1) return