Skip to content

树与二叉树 ​

树是递归思维最自然的载体——一棵树的每个子树,本身还是一棵树。学会"用递归的眼光看树",90% 树题就是填模板。二叉树又是树里最干净的一种——每个节点最多两个孩子,结构简单,套路密集。这一篇讲透二叉树遍历的四种方式、递归和迭代的统一框架,以及神仙级的 Morris 遍历(O(1) 空间)。

一句话先记住:树的本质是"一个根 + 若干子树"。任何树操作都可以拆成"对根做什么 + 递归处理子树"。能把这句话内化,你会觉得二叉树题简单得像抄公式。


一、树的基本概念 ​

         A           ← 根节点(root)
        / \
       B   C
      / \   \
     D   E   F       ← D/E/F 是叶子节点(leaf)

术语速查:

术语含义
根(root)没有父节点的那个
叶子(leaf)没有子节点的那个
度(degree)子节点数
深度(depth)从根到该节点的边数
高度(height)从该节点到最深叶子的边数
祖先 / 后代上面的 / 下面的

二叉树:每个节点最多 2 个子,常叫 left / right。

完全二叉树:除最后一层外都填满,最后一层从左到右填。关键性质:可以用数组紧凑存储——父 i,左子 2i+1,右子 2i+2。堆就是用这个特性。

平衡二叉树:左右子树高度差 ≤ 1,保证 O(log n)。


二、四种遍历 ​

1. 前序(Pre-order):根 → 左 → 右 ​

1
├─ 2
│  ├─ 4
│  └─ 5
└─ 3
遍历序:1, 2, 4, 5, 3

用途:复制树、先处理根再处理子树的所有场景(如打印缩进)。

2. 中序(In-order):左 → 根 → 右 ​

遍历序:4, 2, 5, 1, 3

用途:BST 中序遍历得到升序序列,这是 BST 最重要的性质。

3. 后序(Post-order):左 → 右 → 根 ​

遍历序:4, 5, 2, 3, 1

用途:先处理完子树再处理根——释放内存、算子树大小、算高度。

4. 层序(Level-order / BFS) ​

遍历序:1, 2, 3, 4, 5

用途:按层输出、找最近公共节点、广度优先搜索。靠队列不是递归。


三、递归遍历:三兄弟只差一行 ​

typescript
function preorder(root: TreeNode | null, res: number[]) {
  if (!root) return
  res.push(root.val)              // 根
  preorder(root.left, res)
  preorder(root.right, res)
}

function inorder(root: TreeNode | null, res: number[]) {
  if (!root) return
  inorder(root.left, res)
  res.push(root.val)              // 根在中间
  inorder(root.right, res)
}

function postorder(root: TreeNode | null, res: number[]) {
  if (!root) return
  postorder(root.left, res)
  postorder(root.right, res)
  res.push(root.val)              // 根在最后
}

只有 res.push(root.val) 的位置不同。这就是"对根做什么 + 递归子树"的威力。


四、迭代遍历:用栈模拟递归 ​

前序(简单) ​

typescript
function preorder(root: TreeNode | null): number[] {
  const res: number[] = []
  if (!root) return res
  const stack: TreeNode[] = [root]
  while (stack.length > 0) {
    const node = stack.pop()!
    res.push(node.val)
    if (node.right) stack.push(node.right)  // 先压右
    if (node.left) stack.push(node.left)    // 后压左(先出)
  }
  return res
}

中序(关键:一路往左压栈) ​

typescript
function inorder(root: TreeNode | null): number[] {
  const res: number[] = []
  const stack: TreeNode[] = []
  let cur = root
  while (cur || stack.length > 0) {
    while (cur) { stack.push(cur); cur = cur.left }   // 一路向左
    cur = stack.pop()!
    res.push(cur.val)                                    // 处理
    cur = cur.right                                      // 转向右子树
  }
  return res
}

后序(稍绕:前序变形 + reverse) ​

typescript
function postorder(root: TreeNode | null): number[] {
  const res: number[] = []
  if (!root) return res
  const stack: TreeNode[] = [root]
  while (stack.length > 0) {
    const node = stack.pop()!
    res.unshift(node.val)                // 插到头(等价于根先入栈后出)
    if (node.left) stack.push(node.left)
    if (node.right) stack.push(node.right)
  }
  return res
}

实际上是"根 → 右 → 左"再反转 = 左 → 右 → 根。

层序(队列,不是栈) ​

typescript
function levelOrder(root: TreeNode | null): number[][] {
  const res: number[][] = []
  if (!root) return res
  const queue: TreeNode[] = [root]
  while (queue.length > 0) {
    const size = queue.length
    const level: number[] = []
    for (let i = 0; i < size; i++) {
      const node = queue.shift()!
      level.push(node.val)
      if (node.left) queue.push(node.left)
      if (node.right) queue.push(node.right)
    }
    res.push(level)
  }
  return res
}

记录当前层大小 size,才能分层。这个细节常被忽略。


五、递归模板:树题通用心法 ​

绝大多数二叉树题能套成这个递归模板:

typescript
function solve(root: TreeNode | null): ReturnType {
  // 1. 终止条件
  if (!root) return baseCase

  // 2. 递归处理左右子树,拿到它们的"答案"
  const leftAns = solve(root.left)
  const rightAns = solve(root.right)

  // 3. 用左右的答案 + 当前节点,合成本节点的答案
  return combine(root, leftAns, rightAns)
}

例子一:最大深度 ​

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

例子二:判断平衡二叉树 ​

typescript
function isBalanced(root: TreeNode | null): boolean {
  function height(node: TreeNode | null): number {
    if (!node) return 0
    const l = height(node.left)
    if (l === -1) return -1
    const r = height(node.right)
    if (r === -1) return -1
    if (Math.abs(l - r) > 1) return -1
    return Math.max(l, r) + 1
  }
  return height(root) !== -1
}

用 -1 作为不平衡的哨兵,避免"算了高度再判"两次递归。

例子三:最低公共祖先(LCA) ​

typescript
function lca(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
  if (!root || root === p || root === q) return root
  const left = lca(root.left, p, q)
  const right = lca(root.right, p, q)
  if (left && right) return root       // p 和 q 分别在两侧 → 根就是 LCA
  return left ?? right                  // 都在一侧 → 那侧的结果
}

优雅到让人起鸡皮疙瘩。读懂这个,对递归的理解就通了。


六、Morris 遍历:O(1) 空间 ​

常规迭代用栈,空间 O(h)(h 是树高)。Morris 遍历用**"临时借用叶子节点的 right 指针指回祖先"** 的妖术,空间 O(1)。

中序 Morris ​

typescript
function inorderMorris(root: TreeNode | null): number[] {
  const res: number[] = []
  let cur = root
  while (cur) {
    if (!cur.left) {
      res.push(cur.val)
      cur = cur.right
    } else {
      // 找左子树最右节点
      let pre = cur.left
      while (pre.right && pre.right !== cur) pre = pre.right
      if (!pre.right) {
        pre.right = cur        // 借道:指回 cur
        cur = cur.left
      } else {
        pre.right = null       // 还原
        res.push(cur.val)
        cur = cur.right
      }
    }
  }
  return res
}

核心思想:

  • 每到一个节点,去它左子树的最右节点 → 让那个节点的 right 临时指回当前节点
  • 这样左子树遍历完,能顺着这根"借来的线"回到父节点
  • 回来后把 right 恢复成 null

代价:临时修改树结构,不能并发使用。工程里很少用,面试官可能问"能不能 O(1) 空间遍历"时才亮这招。


七、树题三大常见模式 ​

模式一:自顶向下传参数 ​

typescript
function solve(root, parentInfo) {
  // 把父节点的信息传给子节点
  const myInfo = compute(root, parentInfo)
  solve(root.left, myInfo)
  solve(root.right, myInfo)
}

例:根到叶子的路径和、路径累积计数。

模式二:自底向上聚合 ​

typescript
function solve(root) {
  const left = solve(root.left)
  const right = solve(root.right)
  return combine(root, left, right)
}

例:子树大小、最大深度、判断平衡、LCA。

模式三:层序 + 状态 ​

typescript
while queue not empty:
  size = queue.length
  for i in 0..size:
    节点出队
    处理
    子节点入队

例:按层输出、锯齿遍历、最右节点、每层最大值。


八、常见陷阱 ​

  1. null 判断要早。递归终止条件忘了 if (!root) return,百分百 stack overflow。
  2. 前序是父在前,后序是父在后,中序特供 BST。记乱就全做错。
  3. 深度 vs 高度:从根往下是深度,从叶子往上是高度。高度用后序,深度用前序。
  4. 层序别用 queue.shift() 的 Array——在 JS 里 O(n)。大树会慢。用下标或 deque。
  5. 递归深度:极深的树(退化成链)可能栈溢出。改迭代或 Morris。

九、一句话总结 ​

树题 = "对根做什么 + 递归子树" 的无限变形。递归模板套熟,90% 题是填空;剩下 10% 靠层序 + 队列 / Morris 这些"非递归"解决。遍历四法里,中序专属 BST,后序用于聚合,前序用于向下传,层序用于按层处理——每种各有地盘。

下一篇讲 BST / AVL / 红黑树——"有序"这个性质给了二叉树超能力,也引出了平衡的代价。