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;


    }
相关推荐
怕浪猫2 小时前
GEO 优化到底是什么?AI时代内容创作者必须懂的新技能
算法·面试·github
朝朝辞暮i4 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
Evand J4 小时前
【MATLAB例程】三维RRT+APF避障路径规划与到达角(AOA)定位算法|三维路径优化与定位仿真例程
算法·matlab·路径规划·代码·定位·rrt·aoa
weixin_307779135 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
朝朝辞暮i6 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法
朝朝辞暮i6 小时前
C++ 第 29 课:回调函数 Callback
开发语言·c++·算法
ychqsq7 小时前
207.炸酱面
经验分享·职场和发展
Godspeed Zhao7 小时前
现代智能雷达技术14——算法(0)
线性代数·算法·雷达
可乐ea7 小时前
Agent 模型分级升级路由:用置信度阈值把贵模型省下来
人工智能·算法·机器学习·结构化输出·置信度路由·模型升级路由·大模型成本优化
Navigator_Z7 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode