二叉树是算法中的核心数据结构,掌握遍历和递归是解题关键。

二叉树 (Binary Tree)

二叉树是每个节点最多有两个子节点的树形数据结构。它是算法中最核心的数据结构之一。

// 二叉树节点定义

class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;

  constructor(val: number) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

常见二叉树类型

  • 完全二叉树
  • 满二叉树
  • 二叉搜索树 (BST)
  • 平衡二叉树 (AVL)
  • 红黑树

遍历方式

  • 前序遍历 (根-左-右)
  • 中序遍历 (左-根-右)
  • 后序遍历 (左-右-根)
  • 层序遍历 (BFS)

示例 1: 二叉树遍历

1
2
3
4
5
6
7
遍历结果:
等待遍历...
递归实现
function preorder(node) {
  if (!node) return;
  visit(node.val);  // 根
  preorder(node.left);  // 左
  preorder(node.right); // 右
}
前序遍历 (根-左-右)
适用于:复制树、序列化

示例 2: 二叉树的最大深度(LeetCode 104)

1
2
3
4
5
7
8
function maxDepth(root) {
  if (!root) return 0;

  const leftDepth = maxDepth(root.left);
  const rightDepth = maxDepth(root.right);

  return Math.max(leftDepth, rightDepth) + 1;
}

示例 3: 反转二叉树(LeetCode 226)

这道题源自 Homebrew 作者 Max Howell 的一个经历,是非常经典的递归应用。

4
2
7
1
3
6
9
function invertTree(root) {
  if (!root) return null;

  // 交换左右子树
  [root.left, root.right] = [root.right, root.left];

  // 递归反转子树
  invertTree(root.left);
  invertTree(root.right);

  return root;
}

示例 4: 二叉搜索树 (BST)

二叉搜索树的特点:左子树所有节点 < 根节点 < 右子树所有节点。 查找时间复杂度为 O(log n)。

8
4
12
2
6
10
14
function searchBST(root, val) {
  if (!root) return null;

  if (val === root.val) {
    return root;
  } else if (val < root.val) {
    return searchBST(root.left, val);
  } else {
    return searchBST(root.right, val);
  }
}
BST 中序遍历得到有序序列! 对上面的树进行中序遍历:2 → 4 → 6 → 8 → 10 → 12 → 14