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;
    }
}
相关推荐
科研小白_6 小时前
基于遗传算法优化BP神经网络(GA-BP)的数据时序预测
人工智能·算法·回归
Terry Cao 漕河泾6 小时前
基于dtw算法的动作、动态识别
算法
yaoxin5211236 小时前
211. Java 异常 - Java 异常机制总结
java·开发语言·python
Miraitowa_cheems9 小时前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号9 小时前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区10 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao98511 小时前
BCH码编译码仿真与误码率性能分析
算法
Predestination王瀞潞11 小时前
Java EE开发技术(Servlet整合JDBC银行管理系统-上)
java·servlet·java-ee·jdbc
寻星探路11 小时前
Java EE初阶启程记13---JUC(java.util.concurrent) 的常见类
java·开发语言·java-ee
小白不想白a11 小时前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法