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;


    }
相关推荐
白羊by1 小时前
YOLOv1~v11 全版本核心演进总览
深度学习·算法·yolo
墨尘笔尖3 小时前
最大最小值降采样算法的优化
c++·算法
skylijf4 小时前
2026 高项第 6 章 预测考点 + 练习题(共 12 题,做完稳拿分)
笔记·程序人生·其他·职场和发展·软件工程·团队开发·产品经理
white-persist5 小时前
【vulhub shiro 漏洞复现】vulhub shiro CVE-2016-4437 Shiro反序列化漏洞复现详细分析解释
运维·服务器·网络·python·算法·安全·web安全
FL16238631295 小时前
基于C#winform部署软前景分割DAViD算法的onnx模型实现前景分割
开发语言·算法·c#
baizhigangqw6 小时前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶
算法·启发式算法·web app
C雨后彩虹6 小时前
最多等和不相交连续子序列
java·数据结构·算法·华为·面试
一江寒逸7 小时前
零基础从入门到精通 AI Agent 开发(全栈保姆级教程)附加篇:AI Agent 面试八股文全集
人工智能·面试·职场和发展
久菜盒子工作室7 小时前
面试经验|产品经理|自我介绍
面试·职场和发展·产品经理
cpp_25017 小时前
P2347 [NOIP 1996 提高组] 砝码称重
数据结构·c++·算法·题解·洛谷·noip·背包dp