702 字
4 分钟
二叉树的最大深度
.png)
题目描述
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
解题思路
- 递归分治:
- 终止条件:节点为空时深度为0
- 递归计算左子树深度
leftDepth
- 递归计算右子树深度
rightDepth
- 当前深度 =
max(leftDepth, rightDepth) + 1
- 迭代BFS:
- 使用队列进行层次遍历
- 每层节点遍历完成后深度+1
- 队列为空时返回累计深度
- 迭代DFS:
- 使用栈模拟递归
- 记录每个节点及其当前深度
- 更新全局最大深度
关键洞察
- 深度递归本质:
- 任意节点深度 = 子树最大深度 + 1
- 无需重新计算相同子树
- 后序遍历特性:
- 先处理子节点再处理自身
- 自然获取子树深度信息
- 层次遍历优势:
- 每层明确对应深度级别
- 队列长度 = 当前层节点数
- 空间效率权衡:
- BFS空间取决于最大宽度
- DFS空间取决于树高度
复杂度分析
方法 | 时间复杂度 | 空间复杂度 | 适用场景 |
---|---|---|---|
递归DFS | O(n) | O(h) [树高, 最坏O(n)] | 代码简洁,树平衡时优 |
迭代BFS | O(n) | O(w) [最大宽度] | 需要层次信息时 |
迭代DFS | O(n) | O(h) [树高] | 深度优先需求时 |
代码实现
递归法
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } *//** * @param {TreeNode} root * @return {number} */const maxDepth = (root) => { if (!root) return 0; const left = maxDepth(root.left); const right = maxDepth(root.right); return Math.max(left, right) + 1;};
迭代法 BFS
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } *//** * @param {TreeNode} root * @return {number} */var maxDepth = function (root) { if (!root) return 0; let ans = 0; const queue = [root];
while (queue.length) { let size = queue.length; while (size) { const node = queue.pop(); if (node.left) queue.unshift(node.left); if (node.right) queue.unshift(node.right); size--; } ans++; }
return ans;};
迭代 DFS
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } *//** * @param {TreeNode} root * @return {number} */const maxDepth = (root) => { if (!root) return 0; const stack = [[root, 1]]; // [节点, 当前深度] let max = 0;
while (stack.length) { const [node, depth] = stack.pop(); max = Math.max(max, depth); // 更新最大深度
// 子节点入栈(深度+1) if (node.right) stack.push([node.right, depth + 1]); if (node.left) stack.push([node.left, depth + 1]); } return max;};