二叉树遍历方式代码解读(2迭代)

1.先序遍历(用栈来实现):

java 复制代码
void preOrderIter(TreeNode root) {
    if (root == null) return;

    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);  // 根节点先入栈

    while (!stack.isEmpty()) {
        // 出栈 = 访问
        TreeNode node = stack.pop();
        System.out.print(node.val + " ");

        // 先压右,再压左 → 出栈时就是左先访问
        if (node.right != null) {
            stack.push(node.right);
        }
        if (node.left != null) {
            stack.push(node.left);
        }
    }
}

解读

栈是后进先出

想要访问顺序:根 → 左 → 右

所以入栈必须反过来:先右、后左

出栈自然就是:根 → 左 → 右

2.中序遍历:

java 复制代码
void inOrderIter(TreeNode root) {
    Stack<TreeNode> stack = new Stack<>();
    TreeNode cur = root;  // 当前遍历指针

    while (cur != null || !stack.isEmpty()) {
        // 1. 一路向左走到最深处
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }

        // 2. 左边没了,弹出一个节点访问
        cur = stack.pop();
        System.out.print(cur.val + " ");

        // 3. 转向右子树
        cur = cur.right;
    }
}

解读

核心逻辑:一路左到底 → 访问 → 再右

这是面试必考手写的遍历方式

建议背熟

3.后序遍历:

java 复制代码
void postOrderIter(TreeNode root) {
    if (root == null) return;

    Stack<TreeNode> s1 = new Stack<>();
    Stack<TreeNode> s2 = new Stack<>();

    s1.push(root);

    while (!s1.isEmpty()) {
        TreeNode node = s1.pop();
        s2.push(node);  // 弹出就压入第二个栈

        // 先左后右 → 最终 s2 出栈就是 左→右→根
        if (node.left != null) {
            s1.push(node.left);
        }
        if (node.right != null) {
            s1.push(node.right);
        }
    }

    // s2 依次出栈就是后序
    while (!s2.isEmpty()) {
        System.out.print(s2.pop().val + " ");
    }
}

解读

s1 处理顺序:根 → 右 → 左

压入 s2 后反过来:左 → 右 → 根

最后 s2 依次出栈就是标准后序

相关推荐
Darling噜啦啦5 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
小小工匠6 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾6 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
Qres8216 天前
算法复键——树状数组
数据结构·算法
牛油果子哥q6 天前
并查集(DSU)超精讲,路径压缩、按秩合并、万能模板、连通性判定、最小生成树与刷题实战全解
数据结构·c++·最小生成树·并查集
凌波粒6 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
WL学习笔记6 天前
单项不带头不循环链表
数据结构·链表
小糯米6016 天前
JS 数组
数据结构·算法·排序算法
小欣加油6 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
凌波粒6 天前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode