二叉树遍历方式代码解读(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.莓飛10 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
饮水桶_T14 小时前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
风落青芜21 小时前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
wo_jack1 天前
C++ 入门笔记(十八):list 进阶 —— const 迭代器、operator-> 与 clear 的坑
数据结构·c++·面试·stl·list
ashiho1 天前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
xys_6782 天前
JavaSE通关手册:数组
数据结构
风落青芜2 天前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
老师我太想进步了20264 天前
【数据结构-8】栈的实现
c语言·数据结构·算法
【心态好不摆烂】5 天前
数据结构基础精讲3
数据结构·算法
岑梓铭5 天前
《考研408数据结构》第七章(B树 和 B+树)复习笔记
数据结构·笔记·b树·考研·408