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;


    }
相关推荐
mit6.8241 分钟前
dfs|前后缀分解
算法
扫地的小何尚15 分钟前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
千金裘换酒1 小时前
LeetCode反转链表
算法·leetcode·链表
byzh_rc2 小时前
[认知计算] 专栏总结
线性代数·算法·matlab·信号处理
qq_433554542 小时前
C++ manacher(求解回文串问题)
开发语言·c++·算法
歌_顿3 小时前
知识蒸馏学习总结
人工智能·算法
圣保罗的大教堂3 小时前
leetcode 1161. 最大层内元素和 中等
leetcode
闲看云起3 小时前
LeetCode-day6:接雨水
算法·leetcode·职场和发展
没学上了3 小时前
VLM_一维离散卷积与二维离散卷积(还是复习感觉还行)
算法
黛色正浓4 小时前
leetCode-热题100-贪心合集(JavaScript)
javascript·算法·leetcode