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

【算法与数据结构】 [非递归] 二叉树的先序遍历、中序遍历、后序遍历

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

【算法与数据结构】 [非递归] 二叉树的先序遍历、中序遍历、后序遍历

二叉树的先序遍历

public int[] preorderTraversal (TreeNode root) {
        List list = new ArrayList<>();
        Stack stack = new Stack<>();
        while (!stack.empty() || root!=null){
            while (root!=null){
                list.add(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        int[] ans = new int[list.size()];
        for(int i=0;i
            ans[i] = list.get(i);
        }
        return ans;
    }

二叉树的中序遍历非递归

public int[] inorderTraversal (TreeNode root) {
        List list = new ArrayList<>();
        Stack stack = new Stack<>();
        while (!stack.empty() || root!=null){
            while (root!=null){

                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            list.add(root.val);
            root = root.right;
        }
        int[] ans = new int[list.size()];
        for(int i=0;i
            ans[i] = list.get(i);
        }
        return ans; // write code here
    }

二叉树的后序遍历非递归版本
因为二叉树的先序遍历是:根左右
我们可以通过改变先序顺序得到:根右左
然后对根右左 进行反向遍历就可以得到 左右根

public int[] postorderTraversal (TreeNode root) {
        List list = new ArrayList<>();
        Stack stack = new Stack<>();
        while (!stack.empty() || root!=null){
            while (root!=null){
                list.add(root.val);
                stack.push(root);
                root = root.right;
            }
            root = stack.pop();
            root = root.left;
        }
        int[] ans = new int[list.size()];
        for(int i=ans.length-1;i>=0;i--){
            ans[i-ans.length+1] = list.get(i);
        }
        return ans;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/894700.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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