【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;
    }
相关推荐
mit6.82411 小时前
前后缀分解
算法
Wang's Blog11 小时前
Linux小课堂: 文件操作警惕高危删除命令与深入文件链接机制
linux·运维·服务器
你好,我叫C小白12 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
水月wwww12 小时前
操作系统——进程管理
linux·操作系统·vim·进程·进程调度
我科绝伦(Huanhuan Zhou)13 小时前
分享一个可以一键制作在线yum源的脚本
linux·运维
Paper_Love14 小时前
Linux-查看硬件接口软件占用
linux·运维·服务器
wydaicls14 小时前
Linux 系统下 ZONE 区域的划分
linux·运维·服务器
带土114 小时前
17. Linux wc命令
linux
螺旋小蜗14 小时前
Linux Cgroup与Device Whitelist详解
linux·运维·服务器·cgroup
染指111014 小时前
36.渗透-端口
linux·运维·服务器