LeetCode_145(二叉树的后序遍历)

1.递归

public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        accessTree(root,res);
        return res;
    }
    public void accessTree(TreeNode root, List<Integer> res){
        if(root == null){
            return;
        }

        accessTree(root.left,res);
        accessTree(root.right,res);
        res.add(root.val);
    }

2.循环迭代

public List<Integer> postorderTraversal(TreeNode root) {

        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode prevAccess = null;
        while( root!=null || !stack.isEmpty() ){
            while (root !=null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();

            if(root.right == null || root.right == prevAccess){

                res.add(root.val);
                prevAccess = root;
                root = null;

            }else{
                stack.push(root);
                root = root.right;
            }
        }
        return res;


    }
相关推荐
fai厅的秃头姐!2 小时前
C语言03
c语言·数据结构·算法
lisanndesu2 小时前
动态规划
算法·动态规划
myprogramc2 小时前
十大排序算法
数据结构·算法·排序算法
记得早睡~2 小时前
leetcode150-逆波兰表达式求值
javascript·算法·leetcode
修己xj2 小时前
算法系列之贪心算法
算法
qy发大财2 小时前
跳跃游戏(力扣55)
算法·leetcode
BingLin-Liu3 小时前
蓝桥杯备考:搜索算法之排列问题
算法·职场和发展·蓝桥杯
计算机小白一个3 小时前
蓝桥杯 Java B 组之岛屿数量、二叉树路径和(区分DFS与回溯)
java·数据结构·算法·蓝桥杯
curemoon3 小时前
理解都远正态分布中指数项的精度矩阵(协方差逆矩阵)
人工智能·算法·矩阵
柃歌4 小时前
【UCB CS 61B SP24】Lecture 7 - Lists 4: Arrays and Lists学习笔记
java·数据结构·笔记·学习·算法