【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;
    }
相关推荐
想你依然心痛18 分钟前
嵌入式Linux安全加固:SELinux、Capabilities与Seccomp——强制访问控制与沙箱
linux·运维·安全
KaMeidebaby1 小时前
卡梅德生物技术快报|小 RNA 适配体合成 + 多方法亲和力表征全流程标准化操作手册
前端·网络·数据库·人工智能·算法
是Dream呀1 小时前
基于深度学习的人类行为识别算法研究
人工智能·深度学习·算法
happyprince2 小时前
03_NVIDIA_ModelOpt-量化算法深入
人工智能·深度学习·算法
REDcker2 小时前
macOS 挂载 Linux 远程目录详解
linux·运维·macos
2601_961593422 小时前
Mac 上搭建Linux环境吗?VMware + CentOS Stream 9 镜像快速部署
linux·运维·ide·macos·centos
dddwjzx2 小时前
嵌入式Linux C应用编程入门——线程 (二)
linux·嵌入式
大鱼>2 小时前
AI+货物追踪:智能快递柜追踪系统
人工智能·深度学习·算法·机器学习
写代码的学渣2 小时前
Linux systemd 开机启动日志逐行详细解析报告
linux·运维·服务器
researcher-Jiang3 小时前
算法训练:堆 & 可并堆
算法