2554 字
13 分钟
06 · 二叉树与递归套路
2026-10-13
NOTE

二叉树题的万能框架只有一句话:整棵树的问题 = 处理根 + 左子树的问题 + 右子树的问题。会这句话,前中后序只是”根在什么时候被处理”的区别;而所有”全局最优”类题目,区别只在”返回值该带什么信息”。


1. 递归三要素#

写树的递归,先固定三件事:

  1. 返回值是什么——它携带的是”子树的信息”,不一定是最终答案;
  2. 终止条件是什么——90% 是 if (!root) return ...;
  3. 单层逻辑是什么——拿到左右子树的结果,拼出当前层的答案。
interface TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
}
const node = (val: number, left: TreeNode | null = null, right: TreeNode | null = null): TreeNode =>
({ val, left, right });
// 建一棵小树用于测试:
// 1
// / \
// 2 3
// / \
// 4 5
const tree = node(1, node(2, node(4), node(5)), node(3));

2. 四种遍历:递归与迭代#

2.1 递归版#

function preorder(root: TreeNode | null, res: number[] = []): number[] {
if (!root) return res;
res.push(root.val); // 根先
preorder(root.left, res);
preorder(root.right, res);
return res;
}
function inorder(root: TreeNode | null, res: number[] = []): number[] {
if (!root) return res;
inorder(root.left, res);
res.push(root.val); // 根中(BST 的中序是升序,必背)
inorder(root.right, res);
return res;
}
function postorder(root: TreeNode | null, res: number[] = []): number[] {
if (!root) return res;
postorder(root.left, res);
postorder(root.right, res);
res.push(root.val); // 根后(需要子树结果时用)
return res;
}

选遍历的口诀:

  • 需要”先知道子树才能决定根” → 后序(高度、平衡、直径、路径和);
  • 需要”边走边收集、顺序敏感” → 前序(路径、复制树);
  • 涉及 BST 的有序性 → 中序;
  • 按层处理 → 层序。

2.2 迭代版:栈与队列#

面试常追问”不用递归怎么写”。三种深度优先遍历的迭代写法:

// 前序:根入栈 → 弹出即访问 → 先压右再压左(保证左先出)
function preorderIter(root: TreeNode | null): number[] {
const res: number[] = [];
const stack: TreeNode[] = [];
if (root) stack.push(root);
while (stack.length) {
const n = stack.pop()!;
res.push(n.val);
if (n.right) stack.push(n.right);
if (n.left) stack.push(n.left);
}
return res;
}
// 中序:一路向左压栈,弹出访问后再转向右子树
function inorderIter(root: TreeNode | null): number[] {
const res: number[] = [];
const stack: TreeNode[] = [];
let cur = root;
while (cur || stack.length) {
while (cur) { stack.push(cur); cur = cur.left; }
cur = stack.pop()!;
res.push(cur.val);
cur = cur.right;
}
return res;
}
// 后序:按"根右左"访问再整体反转,得到"左右根"
function postorderIter(root: TreeNode | null): number[] {
if (!root) return [];
const res: number[] = [];
const stack: TreeNode[] = [root];
while (stack.length) {
const n = stack.pop()!;
res.push(n.val);
if (n.left) stack.push(n.left);
if (n.right) stack.push(n.right);
}
return res.reverse();
}

中序迭代是三者里最需要理解的:栈里保存的是”还没访问根的路径”,一路向左到底,弹出时才访问,然后转向右子树。


3. 深度家族:答案依赖子树#

3.1 最大深度#

function maxDepth(root: TreeNode | null): number {
if (!root) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

后序样板:不关心遍历顺序,只关心”左右子树把答案给我,我 +1 返回”。

3.2 最小深度:单边空要特判#

function minDepth(root: TreeNode | null): number {
if (!root) return 0;
if (!root.left) return minDepth(root.right) + 1; // 只有右孩子
if (!root.right) return minDepth(root.left) + 1; // 只有左孩子
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}

坑:只有一个孩子的节点,最小深度不是 1,而是沿非空边走到底。直接写 Math.min(l, r) + 1 会得到 1——这是 111 题唯一的考点。

3.3 平衡二叉树:用 -1 当失败信号#

function isBalanced(root: TreeNode | null): boolean {
return height(root) !== -1;
function height(n: TreeNode | null): number {
if (!n) return 0;
const l = height(n.left);
if (l === -1) return -1; // 提前短路
const r = height(n.right);
if (r === -1) return -1;
return Math.abs(l - r) > 1 ? -1 : Math.max(l, r) + 1;
}
}

把”判断平衡”和”求高度”合并成一次递归,O(n)。对比”对每个节点再调一次 maxDepth”的 O(n²) 暴力版,面试主动报这两个复杂度并说明差异,是很明显的加分点。


4. 全局答案类:返回值与答案分离#

这是树题的分水岭。返回值服务于父节点,答案另外用变量收集。

4.1 二叉树的直径#

function diameterOfBinaryTree(root: TreeNode | null): number {
let ans = 0;
const depth = (n: TreeNode | null): number => {
if (!n) return 0;
const l = depth(n.left);
const r = depth(n.right);
ans = Math.max(ans, l + r); // 以当前节点为"拐点"的路径长度
return Math.max(l, r) + 1; // 返回给父节点的是"单边最大深度"
};
depth(root);
return ans;
}

关键区别:答案可能是 l + r(穿过当前节点),但返回给父节点的只能是 max(l, r) + 1(一条边)。很多人在返回值里直接返回 l + r,结果父节点会用到一条”折线路径”,答案就错了。

4.2 二叉树中的最大路径和#

function maxPathSum(root: TreeNode | null): number {
let ans = -Infinity;
const gain = (n: TreeNode | null): number => {
if (!n) return 0;
const l = Math.max(0, gain(n.left)); // 负贡献不如不要
const r = Math.max(0, gain(n.right));
ans = Math.max(ans, n.val + l + r); // 答案:可以两边都要
return n.val + Math.max(l, r); // 返回:只能选一边
};
gain(root);
return ans;
}

与直径完全同构,只多了两件事:负数分支直接砍掉(取 0),以及答案要包含节点自身的值。


5. 层序 BFS 与三个变体#

function levelOrder(root: TreeNode | null): number[][] {
if (!root) return [];
const res: number[][] = [];
const queue: TreeNode[] = [root];
while (queue.length) {
const size = queue.length; // 必须在本层循环外锁定
const level: number[] = [];
for (let i = 0; i < size; i++) {
const n = queue.shift()!;
level.push(n.val);
if (n.left) queue.push(n.left);
if (n.right) queue.push(n.right);
}
res.push(level);
}
return res;
}

size 必须在 for 循环外取——循环里会 push 下一层节点,边取边变就乱了。这是 BFS 模板最经典的易错点。

5.1 右视图#

function rightSideView(root: TreeNode | null): number[] {
if (!root) return [];
const res: number[] = [];
let queue: TreeNode[] = [root];
while (queue.length) {
res.push(queue[queue.length - 1].val); // 每层最后一个
const next: TreeNode[] = [];
for (const n of queue) {
if (n.left) next.push(n.left);
if (n.right) next.push(n.right);
}
queue = next;
}
return res;
}

5.2 最大宽度:给节点编号#

function widthOfBinaryTree(root: TreeNode | null): number {
if (!root) return 0;
let ans = 0;
let level: Array<[TreeNode, number]> = [[root, 0]];
while (level.length) {
const base = level[0][1]; // 归一化,防止编号溢出
ans = Math.max(ans, level[level.length - 1][1] - base + 1);
const next: Array<[TreeNode, number]> = [];
for (const [n, i] of level) {
const idx = i - base;
if (n.left) next.push([n.left, idx * 2]);
if (n.right) next.push([n.right, idx * 2 + 1]);
}
level = next;
}
return ans;
}

两个细节:编号用 2i / 2i+1;每层要减去该层最左编号,否则深树会把编号撑到超出安全整数范围。


6. 对称、翻转与最近公共祖先#

function invertTree(root: TreeNode | null): TreeNode | null {
if (!root) return null;
[root.left, root.right] = [root.right, root.left];
invertTree(root.left);
invertTree(root.right);
return root;
}
function isSymmetric(root: TreeNode | null): boolean {
const mirror = (a: TreeNode | null, b: TreeNode | null): boolean => {
if (!a && !b) return true;
if (!a || !b) return false;
return a.val === b.val
&& mirror(a.left, b.right)
&& mirror(a.right, b.left);
};
return mirror(root, root);
}

最近公共祖先(236 题)是”返回值携带信息”的最佳教材:

function lowestCommonAncestor(
root: TreeNode | null,
p: TreeNode,
q: TreeNode,
): TreeNode | null {
if (!root || root === p || root === q) return root;
const l = lowestCommonAncestor(root.left, p, q);
const r = lowestCommonAncestor(root.right, p, q);
if (l && r) return root; // p、q 分居两侧 → 当前即是 LCA
return l ?? r; // 只命中一侧 → 继续上传
}

递归函数的含义不是”返回 LCA”,而是**“这棵子树里是否找到了 p 或 q”**——返回值定义对了,代码就三行。

BST 版本可以利用有序性,不用递归到两边:

function lowestCommonAncestorBST(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
while (root) {
if (p.val < root.val && q.val < root.val) root = root.left;
else if (p.val > root.val && q.val > root.val) root = root.right;
else return root; // 分居两侧(或就是其中之一)
}
return null;
}

7. 常见坑#

现象根因解法
BFS 每层数量错乱queue.length 在循环里实时取进 for 前先锁定 size
最小深度恒为 1单边空没特判分别为空时只走另一边
直径答案偏小返回值直接给了 l + r返回 max(l, r) + 1
最大路径和漏负数节点全负树时初始化为 0ans 初始 -Infinity
后序迭代顺序反了忘了整体 reverse按”根右左”收集后反转
BST 中序判断写错只比较父子中序是严格升序,用前驱比较
最大宽度溢出编号未归一化每层减去最左编号
递归爆栈树退化成链改迭代或显式栈

8. 小结#

  • 递归三要素:返回值含义、终止条件、单层逻辑。
  • 四种遍历:递归三件套 + 迭代(前序栈、中序一路向左、后序反转)+ 层序队列。
  • 深度家族:后序”子树给答案我 +1”;最小深度单边空特判;平衡树用 -1 短路。
  • 全局答案类:答案可以是 l + r,返回值只能是一边。
  • 层序变体只改”level 怎么用”;最大宽度要编号并归一化。
  • LCA:返回值携带”是否命中”,BST 版用有序性一路走。

9. 练习(LeetCode 同类题清单)#

    1. 二叉树的最大深度 —— 后序样板,必做。
    1. 翻转二叉树 —— 前序处理根。
    1. 对称二叉树 —— 双参数镜像递归。
    1. 层序遍历 —— BFS 模板,必做。
    1. 二叉树的右视图 —— 层序取每层最后一个。
    1. 平衡二叉树 —— -1 信号短路。
    1. 二叉树的直径 —— 返回值与答案分离。
    1. 二叉树中的最大路径和 —— 同上,注意负数。
    1. 二叉树的最近公共祖先 —— 返回值携带信息。

10. 验收清单#

  • 前/中/后/层序四种遍历都能写(递归 + 迭代各至少一种)
  • 能说出”递归三要素”:终止条件、当前层做什么、返回值含义
  • 层序遍历能说清”为什么进 for 之前要锁定 size”
  • 最大深度、直径、最大路径和这类题能一次写对,并解释”返回值和答案为什么不同”
  • 最小深度的单边空特判能说清,并知道不特判会得到什么
  • 知道递归的空间复杂度是 O(h),退化成链时是 O(n)
  • 测试过:空树、单节点、只有左/右子树、完全二叉树
  • 能在 25 分钟内 AC 一道二叉树中等题
06 · 二叉树与递归套路
https://haolo.cloud/blog/posts/algo-roadmap-06-binary-tree/
作者
Ethan
发布于
2026-10-13
许可协议
CC BY-NC-SA 4.0
本系列目录
算法与手写题 · 共 16 篇 · 当前第 7 篇
  1. 0 总览:前端为什么考算法,30 天怎么刷
  2. 1 复杂度分析与双指针
  3. 2 字符串高频题与正则妙用
  4. 3 哈希表与集合
  5. 4 栈与单调栈
  6. 5 链表专题:虚拟头结点与反转全家桶
  7. 6 二叉树与递归套路 当前
  8. 7 回溯:排列、组合、子集三板斧
  9. 8 动态规划入门:状态定义三步走
  10. 9 动态规划进阶:LIS、编辑距离与区间 DP
  11. 10 手写防抖与节流
  12. 11 手写 Promise 全家桶
  13. 12 手写高频合集:深拷贝、call/bind、instanceof 等
  14. 13 面试策略:沟通、复杂度追问与救场
  15. 14 限时模拟:60 分钟三题,把"会做"变成"做得出来"
  16. 15 堆与图论:TopK、BFS/DFS 与拓扑排序
查看路线总览