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;


    }
相关推荐
Amor风信子10 分钟前
华为OD机试真题---跳房子II
java·数据结构·算法
戊子仲秋27 分钟前
【LeetCode】每日一题 2024_10_2 准时到达的列车最小时速(二分答案)
算法·leetcode·职场和发展
邓校长的编程课堂29 分钟前
助力信息学奥赛-VisuAlgo:提升编程与算法学习的可视化工具
学习·算法
sp_fyf_20241 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-03
人工智能·算法·机器学习·计算机视觉·语言模型·自然语言处理
Eric.Lee20211 小时前
数据集-目标检测系列- 螃蟹 检测数据集 crab >> DataBall
python·深度学习·算法·目标检测·计算机视觉·数据集·螃蟹检测
夜流冰1 小时前
工具方法 - 面试中回答问题的技巧
面试·职场和发展
林辞忧2 小时前
算法修炼之路之滑动窗口
算法
￴ㅤ￴￴ㅤ9527超级帅2 小时前
LeetCode hot100---二叉树专题(C++语言)
c++·算法·leetcode
liuyang-neu2 小时前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
一个不知名程序员www2 小时前
leetcode面试题17.04:消失的数字(C语言版)
leetcode