【leetcode刷题记录】二叉树遍历

中序遍历

java 复制代码
public List<Integer> inorderTraversal(TreeNode root) {
//        List<Integer> result = new ArrayList<>();
//        midAccTree(result,root);
//        return result;

        //栈迭代解决
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            result.add(root.val);
            root = root.right;
        }
        return result;
    }



    //中序遍历方法
//    public void midAccTree(List<Integer> res,TreeNode root){
//        if (root == null) return;
//        midAccTree(res,root.left);
//        res.add(root.val);
//        midAccTree(res,root.right);
//
//    }

后序遍历

java 复制代码
public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode preNode = null;
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == preNode){
                res.add(root.val);
                preNode = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }
相关推荐
runningshark27 分钟前
ARM-DMA
linux·运维·arm开发
小王C语言29 分钟前
优选算法:队列+宽选(bfs)
数据结构·算法·宽度优先
夜雪一千35 分钟前
PostgreSQL 的触发器如何写
linux·数据库·postgresql
LabVIEW开发1 小时前
中大型 LabVIEW 软件怎么分层?界面层、业务层、数据层的拆法与红线
linux·数据库·labview
AI殉道师1 小时前
合因科技三大临床试验数字化模块:EDC + RTSM(IWRS)+ ePRO,从入组到随访如何协同?
科技·算法·临床试验数字化
爆米花byh2 小时前
在RockyLinux9环境的RedRock18.7单机版安装与配置(PostgreSQL 企业级发行版)
linux·数据库·postgresql·database
阿拉丁的梦2 小时前
Pi-Flow-H3-Rev2V+-DWD(极速生成)多参考图生视频+Kandinsky+Video+SR超分放大工作流
linux·服务器·音视频
master3362 小时前
Linux 运维常见问题汇总与实战排障手册
linux·运维
Shaoshing2 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode
不知棋者2 小时前
蓝桥杯 2020 省赛 B 组既约分数:从暴力枚举到欧拉函数前缀和
c++·算法·职场和发展·蓝桥杯