点击下方按钮开始遍历演示
当前树有 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)