栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

二叉树的遍历方式——迭代法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的遍历方式——迭代法

前序遍历(迭代法)中—>左—>右

前序遍历时,每次首先处理的是中间结点,那么先将根节点放入栈中,然后将右孩子加入栈,再加上左孩子。

先加入右孩子,再加入左孩子;这样出栈的时候才是中左右的顺序。

 

public List preorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        Deque stack = new linkedList();
        //Stack stack = new Stack<>();
        if (root == null) {
            return res;
        }
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            //System.out.print(node.val + " ");
            res.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return res;
    }

// 直接打印的版本
public void preorderTraversal(TreeNode root) {
        if (root == null) {
            return res;
        }
        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);
            }
        }
    }

中序遍历(迭代法)中—>左—>右

public static List inOrder(TreeNode root) {
        Stack stack = new Stack<>();
        List res = new ArrayList<>();

        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;     // 左
            }else {
                 root = stack.pop();
                res.add(root.val);    // 中
                root = root.right;    // 右
            }

        }
        return res;
    }

后序遍历(迭代法)左—>右—>中

        将前序遍历的中左右调整为中右左,然后反转res得到左右中 即后序遍历 左-右-中;         

        入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果

// 后序迭代遍历:将前序代码的 中—>左—>右调整为中—>右—>左 然后反转res得到左—>右—>中
    public static List postOrder(TreeNode root) {
        List res = new ArrayList<>();
        Deque stack = new linkedList();
        //Stack stack = new Stack<>();
        if (root == null) {
            return res;
        }
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            //System.out.print(node.val + " ");
            res.add(node.val);
            // 在前序遍历的基础上更改了入栈顺序
            
            if (node.left != null)
                stack.push(node.left);
            if (node.right != null)
                stack.push(node.right);
        }
        Collections.reverse(res);
        return res;

    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/691033.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号