LeetCode 145. 二叉树的后序遍历

145. 二叉树的后序遍历

给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历

示例 1:

复制代码
输入:root = [1,null,2,3]
输出:[3,2,1]

示例 2:

复制代码
输入:root = []
输出:[]

示例 3:

复制代码
输入:root = [1]
输出:[1]

提示:

  • 树中节点的数目在范围 [0, 100]
  • -100 <= Node.val <= 100

**进阶:**递归算法很简单,你可以通过迭代算法完成吗?

解法思路:

1、递归

2、迭代

法一:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        // Recursion
        // Time: O(n)
        // Space: O(n)
        List<Integer> res = new ArrayList<>();
        postorder(root, res);
        return res;
    }

    private void postorder(TreeNode root, List<Integer> res) {
        if (root == null) return;
        postorder(root.left, res);
        postorder(root.right, res);
        res.add(root.val);
    }
}

法二:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        // Iterator
        // Time: O(n)
        // Space: O(n)
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.addLast(root);
                root = root.left;
            }
            root = stack.removeLast();
            if (root.right == null || root.right == prev) {
                res.add(root.val);
                prev = root;
                root = null;
            } else {
                stack.addLast(root);
                root = root.right;
            }
        }
        return res;
    }
}
相关推荐
夏玉林的学习之路11 分钟前
算法8.环形队列
算法
雨辰AI14 分钟前
openGauss 生产运维避坑指南|适配信创项目改造核心难点
java·运维·后端
名字还没想好☜32 分钟前
Java 21 switch 模式匹配实战:sealed 接口 + record 替代 if-instanceof 链
java·人工智能·后端·python·spring
devilnumber40 分钟前
Java 30 组高频技术 / 知识点多角度对比
java·开发语言
摇滚侠1 小时前
《SpringBoot 3:入门与应用实战》第 6 章 Spring Boot 最佳实践 阅读笔记 10
java·spring boot·笔记
O。O蛋黄酥啊1 小时前
GraphRAG 和 LightRAG 详解与对比
人工智能·python·算法·rag·graphrag·lightrag
Σίσυφος19001 小时前
depth_from_focus 详解
算法
圣保罗的大教堂1 小时前
leetcode 2996. 大于等于顺序前缀和的最小缺失整数 简单
leetcode
gugucoding1 小时前
57. 【Java】日志框架:SLF4J与Logback
java·开发语言·logback
今天的砖头有点烫手啊1 小时前
JVM 调优实战:从 GC 日志到参数优化,一次完整排查
java·jvm