【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;
    }
相关推荐
齐齐大魔王1 小时前
linux-僵死进程处理
linux·运维·服务器
wuminyu4 小时前
专家视角看Java字节码加载与存储指令机制
java·linux·c语言·jvm·c++
.小小陈.4 小时前
Linux 线程概念与控制:从底层原理到实战应用
linux·运维·jvm
网络工程小王5 小时前
【LangChain 大模型6大调用指南】调用大模型篇
linux·运维·服务器·人工智能·学习
wangbing11255 小时前
各linux版本的包管理命令
linux·运维·服务器
Joseph Cooper5 小时前
Linux/Android 跟踪技术:ftrace、TRACE_EVENT、atrace、systrace 与 perfetto 入门
android·linux·运维
MediaTea5 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z5 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue5 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
风筝在晴天搁浅6 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法