二叉树遍历方式代码解读(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 依次出栈就是标准后序

相关推荐
h_a_o777oah26 分钟前
【树论】树链剖分:将树形结构转化为线性结构以处理树上路径问题(洛谷 P3384 附C++代码模板)
数据结构·算法·线段树·acm·树链剖分·树论·重链剖分
HEJOO929 分钟前
指针的算术运算详解
java·数据结构·算法
Coder-magician33 分钟前
《代码随想录》刷题打卡day47:并查集-part01
数据结构·算法·图论
垆边人似月.1 小时前
VLAN 资源池(100~200 分档)
数据结构·算法
程序员清风2 小时前
算法与数据结构入门:复杂度、数组与链表
数据结构·算法·链表
Logic1016 小时前
C语言/数据结构排序题解:三个数的最大乘积——排序后比较两种候选情况
c语言·数据结构·数组·排序·时间复杂度·算法题·负数处理
殷色玫瑰7 小时前
C++ string类详解:常用接口、字符串操作与模拟实现
java·linux·c语言·开发语言·数据结构·c++
写后端的胖头鱼8 小时前
时间复杂度 & 空间复杂度
java·数据结构·算法·时间复杂度·空间复杂度
多弗朗皮卡丘8 小时前
数据结构番外:环形队列
数据结构·c
50万马克的面包9 小时前
顺序表和链表_精华知识点_CSDN博客
数据结构·链表