【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;
    }
相关推荐
maosheng11463 小时前
RHCSA的第一次作业
linux·运维·服务器
wifi chicken4 小时前
Linux 端口扫描及拓展
linux·端口扫描·网络攻击
旺仔.2914 小时前
Linux 信号详解
linux·运维·网络
放飞梦想C4 小时前
CPU Cache
linux·cache
I_LPL4 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱4 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
Hoshino.415 小时前
基于Linux中的数据库操作——下载与安装(1)
linux·运维·数据库
WolfGang0073215 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
2401_831824966 小时前
代码性能剖析工具
开发语言·c++·算法
播播资源6 小时前
CentOS系统 + 宝塔面板 部署 OpenClaw源码开发版完整教程
linux·运维·centos