【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;
    }
相关推荐
CoovallyAIHub10 分钟前
基于YOLO集成模型的无人机多光谱风电部件缺陷检测
深度学习·算法·计算机视觉
CoovallyAIHub11 分钟前
几十个像素的小目标,为何难倒无人机?LCW-YOLO让无人机小目标检测不再卡顿
深度学习·算法·计算机视觉
怀旧,22 分钟前
【C++】19. 封装红⿊树实现set和map
linux·c++·算法
往事随风去31 分钟前
Redis的内存淘汰策略(Eviction Policies)有哪些?
redis·后端·算法
敲上瘾1 小时前
Docker 存储卷(Volume)核心概念、类型与操作指南
linux·服务器·数据库·docker·容器·架构
神里流~霜灭1 小时前
(C++)数据结构初阶(顺序表的实现)
linux·c语言·数据结构·c++·算法·顺序表·单链表
一只乔哇噻1 小时前
java后端工程师进修ing(研一版 || day41)
java·开发语言·学习·算法
愚润求学1 小时前
【贪心算法】day7
c++·算法·leetcode·贪心算法
禁默2 小时前
已知 inode 号,如何操作文件?Ext 文件系统增删查改底层逻辑拆解
linux·服务器·数据库
许怀楠2 小时前
【Linux】基础指令(下)
linux