
解题思路(递归):
- 终止条件: 若节点为空,返回深度0。
- 递归步骤: 分别计算左子树和右子树的最大深度,取较大者并加1(当前节点)。
Java代码:
class Solution {public int maxDepth(TreeNode root) {if (root == null) return 0;return Math.max(maxDepth(root.left) + 1, maxDepth(root.right) + 1);}
}
复杂度分析:
- 时间复杂度: O(n), 需访问每个节点一次。
- 空间复杂度: 递归调用栈的深度取决于树的高度 h,最坏情况(树为链表)空间复杂度为 O(n),平衡树时为 O(log n)。
解题思路(BFS):
- 层次遍历: 逐层处理节点,每处理一层深度加1。若节点为空,返回深度0。
- 队列实现: 利用队列存储当前层所有节点,循环处理直至队列为空。
Java代码:
class Solution {public int maxDepth(TreeNode root) {if (root == null) return 0;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);int depth = 0;while (!queue.isEmpty()) {depth++;int levelSize = queue.size();for (int i = 0; i < levelSize; i++) {TreeNode node = queue.poll();if (node.left != null) queue.offer(node.left);if (node.right != null) queue.offer(node.right);}}return depth;}
}
复杂度分析:
- 时间复杂度: O(n), 需访问每个节点一次。
- 空间复杂度: 队列最多存储一层节点,最坏情况(完全二叉树)空间复杂度为 O(n)。

解题思路(递归):
- 终止条件: 当前节点为空时返回 null,当前节点没有子树时返回当前节点。
- 递归步骤: 递归翻转左子树和右子树,然后交换当前节点的左子节点和右子节点。
Java代码:
class Solution {public TreeNode invertTree(TreeNode root) {if (root == null) return null;if (root.left == null && root.right == null) return root;TreeNode left = invertTree(root.left);TreeNode right = invertTree(root.right);root.left = right;root.right = left;return root;}
}
复杂度分析:
- 时间复杂度: O(n),需访问每个节点一次。
- 空间复杂度: 递归调用栈的深度为树的高度 h,最坏情况(链状树)空间复杂度为 O(n)。