【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;
    }
相关推荐
有谁看见我的剑了?16 分钟前
ubuntu 22.04 wifi网卡配置地址上网
linux·运维·ubuntu
水水沝淼㵘18 分钟前
嵌入式开发学习日志(数据结构--单链表)Day20
c语言·开发语言·数据结构·学习·算法
算法给的安全感20 分钟前
bfs-最小步数问题
java·算法·宽度优先
码农新猿类23 分钟前
Ubuntu摄像头打开失败
linux·运维·ubuntu
灏瀚星空34 分钟前
地磁-惯性-视觉融合制导系统设计:现代空战导航的抗干扰解决方案
图像处理·人工智能·python·深度学习·算法·机器学习·信息与通信
PWRJOY1 小时前
Ubuntu磁盘空间分析:du命令及常用组合
linux·运维·ubuntu
田梓燊1 小时前
专业课复习笔记 7
笔记·算法
ASDyushui1 小时前
Shell 编程之正则表达式与文本处理器
linux·正则表达式
健康胡1 小时前
仿射变换 与 透视变换
图像处理·人工智能·深度学习·opencv·算法·机器学习·计算机视觉
L_cl1 小时前
【Python 算法零基础 2.模拟 ④ 基于矩阵】
python·算法·矩阵