🧠 引言
还在背“前中后层”遍历口诀?
学了半天二叉树,却还是搞不清“递归遍历”“非递归栈模拟”“层序 BFS”?
别怕,这篇文章带你从 0 到 1,不光用图解讲透二叉树的基本结构和遍历方式,还会用 JavaScript 和 Python 双语演示,彻底吃透这个经典结构!
🌳 一、什么是二叉树?
二叉树(Binary Tree)是一种每个节点最多有两个子节点(左子 + 右子)的树形结构。
结构示意:
A
/ \
B C
/ \ \
D E F
🧱 二、定义二叉树节点结构
✅ JavaScript 实现
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
✅ Python 实现
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
🔁 三、四种遍历方式(递归版)
📘 前序遍历(根 → 左 → 右)
JS:
function preorder(node) {
if (!node) return;
console.log(node.val);
preorder(node.left);
preorder(node.right);
}
Python:
def preorder(node):
if not node:
return
print(node.val)
preorder(node.left)
preorder(node.right)
📘 中序遍历(左 → 根 → 右)
JS:
function inorder(node) {
if (!node) return;
inorder(node.left);
console.log(node.val);
inorder(node.right);
}
Python:
def inorder(node):
if not node:
return
inorder(node.left)
print(node.val)
inorder(node.right)
📘 后序遍历(左 → 右 → 根)
JS:
function postorder(node) {
if (!node) return;
postorder(node.left);
postorder(node.right);
console.log(node.val);
}
Python:
def postorder(node):
if not node:
return
postorder(node.left)
postorder(node.right)
print(node.val)
📘 层序遍历(按层打印)
JS:
function levelOrder(root) {
if (!root) return;
const queue = [root];
while (queue.length) {
const node = queue.shift();
console.log(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
Python:
from collections import deque
def level_order(root):
if not root:
return
queue = deque([root])
while queue:
node = queue.popleft()
print(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
🧪 四、构造示例树并运行
A
/ \
B C
/ \ \
D E F
JS 创建树:
const A = new TreeNode('A');
const B = new TreeNode('B');
const C = new TreeNode('C');
const D = new TreeNode('D');
const E = new TreeNode('E');
const F = new TreeNode('F');
A.left = B;
A.right = C;
B.left = D;
B.right = E;
C.right = F;
Python 创建树:
A = TreeNode('A')
B = TreeNode('B')
C = TreeNode('C')
D = TreeNode('D')
E = TreeNode('E')
F = TreeNode('F')
A.left = B
A.right = C
B.left = D
B.right = E
C.right = F
⚠️ 五、常见错误分析
错误 | 解释 |
---|---|
遍历顺序写错 | 写成“左右根”结果变成后序遍历 |
忘记递归出口 | 可能导致死循环或栈溢出 |
层序忘记判断子节点存在 | push 前需判断是否非空 |
忘记 .shift() 的副作用 | JS 中 shift 是 O(n) 操作,频繁使用需注意 |
🧩 六、拓展挑战任务
- 实现非递归版中序遍历(用栈模拟)
- 实现树的最大深度函数
- 实现一个判断二叉树是否对称的函数
📌 总结一句话
二叉树是算法世界中的“高频演员”,掌握它就等于掌握了大半的树形问题套路!
下一篇预告:
📘 第6篇:【动态数组底层结构揭秘】ArrayList/Vector 是怎么扩容的?