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;


    }
相关推荐
空白到白33 分钟前
机器学习-聚类
人工智能·算法·机器学习·聚类
索迪迈科技39 分钟前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
zzzsde1 小时前
【数据结构】队列
数据结构·算法
芒克芒克1 小时前
LeetCode 面试经典 150 题:删除有序数组中的重复项(双指针思想解法详解)
算法
青 .1 小时前
数据结构---二叉搜索树的实现
c语言·网络·数据结构·算法·链表
MChine慕青2 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表
塔中妖2 小时前
【华为OD】查找接口成功率最优时间段
算法·链表·华为od
塔中妖2 小时前
【华为OD】最大子矩阵和
算法·华为od·矩阵
努力学习的小廉3 小时前
深入了解linux系统—— 线程同步
linux·服务器·数据库·算法