LeetCode(力扣):二叉树的后序遍历

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) {
        //需要使用addFirst()插到头部,所以使用LinkedList
        LinkedList<Integer> result = new LinkedList<>();

        if(root == null){
            return result;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            //永远将拿到的节点的值放到最前面
            result.addFirst(node.val);

            if(node.left != null){
                stack.push(node.left);
            }

            if(node.right != null){
                stack.push(node.right);
            }
        }
        return result;
    }
}
相关推荐
luj_17683 分钟前
一线一区一变破解人盯人防守密码
开发语言·网络·c++·经验分享·算法
Wang's Blog26 分钟前
Java框架快速入门: Spring Security+OAuth2之字段验证与自定义验证注解实战
java·算法·spring
带多刺的玫瑰32 分钟前
Leecode#29刷题之两数相除
java·python·算法
smj2302_7968265234 分钟前
解决leetcode第4017题数组中的峰值II
python·算法·leetcode
午彦琳38 分钟前
2026.9.9
数据结构·算法·leetcode
luj_176841 分钟前
中锋卡位与开放线博弈
c语言·开发语言·网络·经验分享·算法
洋不写bug1 小时前
二叉树(四)经典算法题目解析,公共祖先,二叉树构造,非递归遍历
数据库·算法·二叉树·二叉树构造·公共祖先
hansang_IR1 小时前
【题解】P4454 [CQOI2018] 破解D-H协议
c++·算法·密码学·数论
梓䈑1 小时前
【动态规划系列】路径问题、子数组 和 子序列问题、背包问题
c++·算法·动态规划
aqiu1111111 小时前
【数位 DP / 记忆化搜索】蓝桥云课 - 光轨区的 AI 数 题解
c++·算法·蓝桥杯·数位dp