树与二叉树遍历
树是分层数据的自然形态:文件系统、组织架构、HTML DOM、数据库索引。二叉树是树的特例(每个节点最多两个孩子),却撑起了算法面试的半壁江山——因为二叉树是递归思想的最佳训练场。绝大多数树的题,想清楚递归三条线(base case、当前层做什么、递归方向),代码自然就写出来了。
术语与形态
1 ← 根节点(root)
/ \
2 3 ← 内部节点
/ \ \
4 5 6 ← 叶子节点(leaf,无孩子)- 深度:从根到该节点的边数(根深度 0)
- 高度:从该节点到最深叶子的边数(树高 = 根的高度)
- 层:深度相同的节点构成一层(根在第 0 层)
常见形态:
| 类型 | 特点 |
|---|---|
| 满二叉树 | 每层都满,节点数 2^h - 1 |
| 完全二叉树 | 除最后一层外都满,最后一层靠左——堆的实现基础 |
| 二叉搜索树(BST) | 左子树全部小于根,右子树全部大于根 |
| 平衡树(AVL/红黑) | 左右子树高度差 ≤ 1(或颜色约束),防止退化 |
Rust 里的树节点
#[derive(Debug)]
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
impl TreeNode {
fn new(val: i32) -> Self {
TreeNode { val, left: None, right: None }
}
}
// 构造: 1
// / \
// 2 3
fn build() -> Option<Box<TreeNode>> {
let mut root = Box::new(TreeNode::new(1));
root.left = Some(Box::new(TreeNode::new(2)));
root.right = Some(Box::new(TreeNode::new(3)));
Some(root)
}Option<Box<TreeNode>> 的组合前面说过——None 表示空孩子,Box 放堆上。所有树的题都是在这个结构上做遍历。
四种遍历:递归的四个模板
前序遍历(根 → 左 → 右)
fn preorder(node: &Option<Box<TreeNode>>, result: &mut Vec<i32>) {
if let Some(n) = node {
result.push(n.val); // 先访问根
preorder(&n.left, result); // 再左
preorder(&n.right, result); // 后右
}
}中序遍历(左 → 根 → 右)
fn inorder(node: &Option<Box<TreeNode>>, result: &mut Vec<i32>) {
if let Some(n) = node {
inorder(&n.left, result);
result.push(n.val); // 中间访问根
inorder(&n.right, result);
}
}BST 的中序遍历结果是升序序列——这是 BST 最重要的性质,验证 BST、找第 k 小、两数之和,全用它。
后序遍历(左 → 右 → 根)
fn postorder(node: &Option<Box<TreeNode>>, result: &mut Vec<i32>) {
if let Some(n) = node {
postorder(&n.left, result);
postorder(&n.right, result);
result.push(n.val); // 最后访问根
}
}后序的典型应用:自底向上统计(子树高度、子树和、删除节点)。因为"先处理完孩子才能处理自己"。
层序遍历(BFS)
use std::collections::VecDeque;
fn level_order(root: &Option<Box<TreeNode>>) -> Vec<Vec<i32>> {
let mut result = Vec::new();
if root.is_none() {
return result;
}
let mut queue: VecDeque<&Box<TreeNode>> = VecDeque::new();
queue.push_back(root.as_ref().unwrap());
while !queue.is_empty() {
let level_size = queue.len(); // 当前层有几个节点
let mut level = Vec::with_capacity(level_size);
for _ in 0..level_size {
let node = queue.pop_front().unwrap();
level.push(node.val);
if let Some(l) = &node.left {
queue.push_back(l);
}
if let Some(r) = &node.right {
queue.push_back(r);
}
}
result.push(level);
}
result
}关键:进入循环时先取 queue.len()——那是当前层的节点数。 弹出这么多、压入下一层,天然分层。忘了这步,所有节点混在一起,得不到"每层一个数组"的结果。
迭代遍历:不用递归怎么写
递归有爆栈风险(树深 10 万时)。迭代版必须掌握,且常作为面试加分项。
前序迭代:栈模拟
fn preorder_iter(root: &Option<Box<TreeNode>>) -> Vec<i32> {
let mut result = Vec::new();
let mut stack: Vec<&Box<TreeNode>> = Vec::new();
if let Some(r) = root {
stack.push(r);
}
while let Some(node) = stack.pop() {
result.push(node.val);
// 先压右再压左——出栈顺序才是 左→右
if let Some(r) = &node.right {
stack.push(r);
}
if let Some(l) = &node.left {
stack.push(l);
}
}
result
}"先压右孩子"是精髓——栈是后进先出,想先处理左,就得后压左。
中序迭代:一路向左
fn inorder_iter(root: &Option<Box<TreeNode>>) -> Vec<i32> {
let mut result = Vec::new();
let mut stack: Vec<&Box<TreeNode>> = Vec::new();
let mut cur = root.as_ref();
while cur.is_some() || !stack.is_empty() {
// 一路向左,沿途入栈
while let Some(node) = cur {
stack.push(node);
cur = node.left.as_ref();
}
// 到最左,弹出访问,转向右子树
let node = stack.pop().unwrap();
result.push(node.val);
cur = node.right.as_ref();
}
result
}这个"先一路向左入栈、再弹出一个转右"的模式,是 BST 迭代器的标准实现(LeetCode 173 题)。
后序迭代:前序的变形
后序迭代的巧解:前序是 根→左→右,反过来就是 右→左→根。用前序迭代的模板,把左右孩子入栈顺序对调,最后整个结果反转,就是后序。
fn postorder_iter(root: &Option<Box<TreeNode>>) -> Vec<i32> {
let mut result = Vec::new();
let mut stack: Vec<&Box<TreeNode>> = Vec::new();
if let Some(r) = root {
stack.push(r);
}
while let Some(node) = stack.pop() {
result.push(node.val);
if let Some(l) = &node.left { // 与"前序迭代"对调
stack.push(l);
}
if let Some(r) = &node.right {
stack.push(r);
}
}
result.reverse(); // 最后反转
result
}递归解题框架:想清楚三件事
树的递归题,按这个顺序想,百发百中:
一、这个函数返回什么?(给子树算高度?算节点数?找路径?) 二、当前节点这一层做什么?(拿左右孩子的结果怎么组合?) 三、base case 是什么?(空节点返回什么?)
例一:最大深度
fn max_depth(node: &Option<Box<TreeNode>>) -> i32 {
match node {
None => 0, // base case
Some(n) => 1 + max_depth(&n.left).max(max_depth(&n.right)), // 当前层:1 + 左右最大
}
}例二:翻转二叉树
fn invert(node: &mut Option<Box<TreeNode>>) {
if let Some(n) = node {
// 当前层:交换左右
std::mem::swap(&mut n.left, &mut n.right);
// 递归:左右各自翻转
invert(&mut n.left);
invert(&mut n.right);
}
}例三:路径总和(判断有没有根到叶子的路径和为目标)
fn has_path_sum(node: &Option<Box<TreeNode>>, target: i32) -> bool {
match node {
None => false,
Some(n) => {
// 叶子节点:差值刚好为 0
if n.left.is_none() && n.right.is_none() {
return n.val == target;
}
let remain = target - n.val;
has_path_sum(&n.left, remain) || has_path_sum(&n.right, remain)
}
}
}注意叶子判断:路径必须到叶子结束,中间节点不算。这类"边界条件"是面试挂人的高发区。
例四:最近公共祖先(LCA)
fn lowest_common_ancestor(
node: &Option<Box<TreeNode>>,
p: i32,
q: i32,
) -> Option<i32> {
let n = node.as_ref()?;
// p 或 q 之一就是当前节点,当前节点就是 LCA
if n.val == p || n.val == q {
return Some(n.val);
}
let left = lowest_common_ancestor(&n.left, p, q);
let right = lowest_common_ancestor(&n.right, p, q);
match (left, right) {
(Some(l), Some(r)) => Some(n.val), // 一边一个,当前节点是分叉点
(Some(l), None) => Some(l), // 都在左边
(None, Some(r)) => Some(r), // 都在右边
(None, None) => None, // 都没有
}
}LCA 是"后序思想"的代表:左右子树的结果都回来了,才能决定当前节点是不是答案。
二叉搜索树(BST)
BST 的中序遍历升序,由此派生一整类题。
验证 BST
fn is_valid_bst(node: &Option<Box<TreeNode>>) -> bool {
fn helper(n: &Option<Box<TreeNode>>, low: Option<i32>, high: Option<i32>) -> bool {
match n {
None => true,
Some(node) => {
if let Some(l) = low {
if node.val <= l { return false; }
}
if let Some(h) = high {
if node.val >= h { return false; }
}
helper(&node.left, low, Some(node.val))
&& helper(&node.right, Some(node.val), high)
}
}
}
helper(node, None, None)
}为什么不能只判断"左孩子 < 根 < 右孩子"? 因为 BST 要求整棵子树满足范围约束。反例:根 10,左孩子 5,5 的右孩子 15——局部合法,但 15 在根左边,全局非法。所以递归要带上下界。
BST 查找
fn search_bst(node: &Option<Box<TreeNode>>, target: i32) -> bool {
match node {
None => false,
Some(n) => {
if n.val == target {
true
} else if target < n.val {
search_bst(&n.left, target) // 小的走左边
} else {
search_bst(&n.right, target)
}
}
}
}每步排除一半,O(log n)——平衡树的前提下。退化成链表(插入有序数据)就成 O(n),所以生产用平衡树(红黑树)。
BST 插入
fn insert_bst(node: &mut Option<Box<TreeNode>>, val: i32) {
match node {
None => {
*node = Some(Box::new(TreeNode::new(val)));
}
Some(n) => {
if val < n.val {
insert_bst(&mut n.left, val);
} else if val > n.val {
insert_bst(&mut n.right, val);
}
// 相等:不插入(或计数,看需求)
}
}
}第 K 小的元素
中序遍历计数,数到第 k 个返回。O(k),不需要遍历全树。
树的序列化与反序列化
前序序列化 + 空节点标记,是面试常考:
// 序列化:"1,2,None,None,3,4,None,None,5,None,None"
fn serialize(node: &Option<Box<TreeNode>>) -> String {
fn helper(n: &Option<Box<TreeNode>>, out: &mut String) {
match n {
None => out.push_str("None,"),
Some(node) => {
out.push_str(&node.val.to_string());
out.push(',');
helper(&node.left, out);
helper(&node.right, out);
}
}
}
let mut out = String::new();
helper(node, &mut out);
out
}反序列化就是拿个迭代器按同样顺序重建。LeetCode 297,hard 里偏简单的。
面试高频题清单
| 题 | 考点 | 遍历方式 |
|---|---|---|
| 最大深度 | 后序,取孩子最大值 | 递归 |
| 翻转二叉树 | 交换 + 递归 | 前序 |
| 对称二叉树 | 左右镜像比较 | 双递归 |
| 路径总和 I/II/III | 回溯 + 累加 | 前序 |
| 最近公共祖先 | 后序,左右组合 | 后序 |
| 从中序+前序重建树 | 递归分治 | 前序定位根 |
| 验证 BST | 上下界约束 | 中序 |
| BST 第 K 小 | 中序计数 | 中序 |
| 层序遍历 | BFS 分层 | 层序 |
| 右视图 | 每层最后一个 | 层序 |
| 锯齿遍历 | 奇偶层反转 | 层序 |
| 完全二叉树节点数 | 利用完全树性质,O(log²n) | 二分 + 高度 |
小结
树的四种遍历是根:前中后序(DFS)+ 层序(BFS),递归版三行一个,迭代版靠栈和队列。解题框架三问:返回什么、当前层做什么、base case 是什么。BST 记住中序升序,一切性质推导从这出发。经典组合拳:LCA 用后序、路径和用回溯、分层用层序、范围约束用中序。下一篇堆与优先队列。
