🌲 二叉树 Binary Tree 可视化
每个节点最多有两个子节点。掌握四种遍历方式是理解树结构的关键
点击下方按钮开始遍历演示
当前树有 7 个节点
JavaScript 实现
// 二叉树节点 class TreeNode { constructor(val) { this.val = val; this.left = null; this.right = null; } } // 前序遍历:根 → 左 → 右 function preorder(node, result = []) { if (!node) return result; result.push(node.val); // 先访问根 preorder(node.left, result); // 再左子树 preorder(node.right, result); // 后右子树 return result; } // 中序遍历:左 → 根 → 右(BST得到有序序列) function inorder(node, result = []) { if (!node) return result; inorder(node.left, result); // 先左子树 result.push(node.val); // 再访问根 inorder(node.right, result); // 后右子树 return result; } // 后序遍历:左 → 右 → 根(删除节点用) function postorder(node, result = []) { if (!node) return result; postorder(node.left, result); // 先左子树 postorder(node.right, result); // 再右子树 result.push(node.val); // 后访问根 return result; } // 层序遍历:逐层从上到下(BFS,用队列) function levelOrder(root) { const result = []; if (!root) return result; const queue = [root]; while (queue.length > 0) { const node = queue.shift(); result.push(node.val); if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } return result; }
复杂度与遍历特性
| 遍历方式 | 顺序 | 时间复杂度 | 空间复杂度 | 应用场景 |
|---|---|---|---|---|
| 前序遍历 | 根→左→右 | O(n) | O(h) | 复制树、序列化 |
| 中序遍历 | 左→根→右 | O(n) | O(h) | BST有序输出 |
| 后序遍历 | 左→右→根 | O(n) | O(h) | 删除树、表达式求值 |
| 层序遍历 | 逐层 | O(n) | O(w) | BFS、最短路径 |
h = 树的高度,w = 树的最大宽度。平衡树 h = O(log n),退化链表 h = O(n)