【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;
    }
相关推荐
jianglq几秒前
C++20 协程:异步编程的新纪元
算法·c++20
Hadoop_Liang36 分钟前
xshell密钥方式连接阿里云Linux
linux·阿里云·云计算
wniuniu_38 分钟前
动态规划前---选----
算法·动态规划
lzb_kkk2 小时前
【Redis】redis5种数据类型(哈希)
开发语言·redis·算法·缓存·哈希算法
鱼跃鹰飞2 小时前
Leetcode面试经典150题-202.快乐数
算法·leetcode·面试
鱼跃鹰飞2 小时前
Leetcode面试经典150题-82.删除排序链表中的重复元素II
算法·leetcode·面试
CS_素锦少年3 小时前
Linux_kernel驱动开发11
linux·运维·驱动开发
结衣结衣.4 小时前
Linux——进程状态
linux·运维·服务器·c语言·笔记·学习
云边有个稻草人4 小时前
【刷题】Day4--密码检查
开发语言·数据结构·笔记·算法
li星野4 小时前
面试问题001
linux·开发语言·面试