2026-03-28 20:37:24
LeetCode 104. 二叉树的最大深度题解如下:
两种方法时间复杂度均为O(N),递归法空间复杂度取决于树高,迭代法空间复杂度为O(N)。
方法一:递归算法思路:
Java代码:
class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return Math.max(leftDepth, rightDepth) + 1; }}Python代码:
class Solution: def maxDepth(self, root): if not root: return 0 left_depth = self.maxDepth(root.left) right_depth = self.maxDepth(root.right) return max(left_depth, right_depth) + 1复杂度分析:
最坏情况(树退化为链表):O(N)。
最好情况(完全平衡树):O(logN)。
算法思路:
Java代码:
import javafx.util.Pair;import java.util.LinkedList;import java.util.Queue;class Solution { public int maxDepth(TreeNode root) { Queue<Pair<TreeNode, Integer>> stack = new LinkedList<>(); if (root != null) { stack.add(new Pair<>(root, 1)); } int depth = 0; while (!stack.isEmpty()) { Pair<TreeNode, Integer> current = stack.poll(); root = current.getKey(); int currentDepth = current.getValue(); if (root != null) { depth = Math.max(depth, currentDepth); stack.add(new Pair<>(root.left, currentDepth + 1)); stack.add(new Pair<>(root.right, currentDepth + 1)); } } return depth; }}Python代码:
class Solution: def maxDepth(self, root): stack = [] if root: stack.append((1, root)) depth = 0 while stack: current_depth, root = stack.pop() if root: depth = max(depth, current_depth) stack.append((current_depth + 1, root.left)) stack.append((current_depth + 1, root.right)) return depth复杂度分析:
根据树的结构和编程环境选择合适方法。递归法在平衡树中空间效率更高,而迭代法在极端情况下更稳定。