【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;
    }
相关推荐
leafseelight2 小时前
在CentOS 7上添加Swap交换空间完整指南
linux·运维·centos
van_peak2 小时前
Centos 9 Could not resolve host: mirrors.centos.org问题
linux·运维·centos
yonuyeung2 小时前
代码随想录算法【Day57】
数据结构·算法
likfishdn2 小时前
CentOS修改yum源
linux·centos
福旺旺2 小时前
Linux实操——在服务器上直接从百度网盘下载(/上传)文件
linux·服务器
居然有人6542 小时前
27.贪心算法5
算法·贪心算法
IU宝3 小时前
Linux的部分常用基础指令
linux·服务器
夏末秋也凉3 小时前
力扣-动态规划-62 不同路径
算法·leetcode·动态规划
zeandon3 小时前
VMware未识别到SD卡插入
linux
qq_448941083 小时前
实验:k8s+keepalived+nginx+iptables
linux·运维·服务器