【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;
    }
相关推荐
徐小夕39 分钟前
JitWord 3.0 正式发布,高精度Word异构解析+复杂组件兼容,打造web端协同Word编辑器
前端·vue.js·算法
摇滚侠16 小时前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
通信小呆呆16 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
bush416 小时前
嵌入式linux学习记录十四、术语
linux·嵌入式
benben04416 小时前
强化学习之DQN算法族(基于gymnasium开发)
算法
载数而行52016 小时前
Linux 11 动态监控指令top
linux
何以解忧,唯有..17 小时前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
不会C语言的男孩18 小时前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言
古城小栈18 小时前
Unix 与 Linux 异同小叙
linux·服务器·unix