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;


    }
相关推荐
只与明月听5 分钟前
前端学算法-二叉树(一)
前端·javascript·算法
电院工程师17 分钟前
SM3算法Python实现(无第三方库)
开发语言·python·算法·安全·密码学
小刘同学++1 小时前
用 OpenSSL 库实现 3DES(三重DES)加密
c++·算法·ssl
写写闲篇儿2 小时前
搜索二维矩阵
线性代数·算法·矩阵
LunaGeeking2 小时前
重要的城市(图论 最短路)
c++·算法·编程·图论·最短路·floyd
刘小小_算法工程师2 小时前
「ECG信号处理——(17)基于小波熵阈值的R峰检测(与时域-频域-多尺度小波法对比)」2025年6月12日
算法·信号处理
电控极客2 小时前
电动汽车驱动模式扭矩控制设计方法
经验分享·算法·汽车·策略模式
jz_ddk3 小时前
[python] 使用python设计滤波器
开发语言·python·学习·算法
1白天的黑夜13 小时前
二叉树-226.翻转链表-力扣(LeetCode)
数据结构·c++·leetcode
快乐肚皮3 小时前
快速排序优化技巧详解:提升性能的关键策略
java·算法·性能优化·排序算法