Java | Leetcode Java题解之第145题二叉树的后序遍历

题目:

题解:

java 复制代码
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }

        TreeNode p1 = root, p2 = null;

        while (p1 != null) {
            p2 = p1.left;
            if (p2 != null) {
                while (p2.right != null && p2.right != p1) {
                    p2 = p2.right;
                }
                if (p2.right == null) {
                    p2.right = p1;
                    p1 = p1.left;
                    continue;
                } else {
                    p2.right = null;
                    addPath(res, p1.left);
                }
            }
            p1 = p1.right;
        }
        addPath(res, root);
        return res;
    }

    public void addPath(List<Integer> res, TreeNode node) {
        int count = 0;
        while (node != null) {
            ++count;
            res.add(node.val);
            node = node.right;
        }
        int left = res.size() - count, right = res.size() - 1;
        while (left < right) {
            int temp = res.get(left);
            res.set(left, res.get(right));
            res.set(right, temp);
            left++;
            right--;
        }
    }
}
相关推荐
nice_lcj5201 小时前
Bean 的作用域:单例、原型及特殊作用域
java·spring·面试·原型·单例·bean作用域
这个昵称不容易3 小时前
SpringBoot 基于web的酒店客房管理系统设计与实现:176 个 Java 文件 233 个接口,会员预约到退房一条链
java·springboot·毕设
nice_lcj5203 小时前
Spring AOP 面向切面编程:切面解决什么问题
java·spring·面试·aop·切面·面向切面编程
考虑考虑3 小时前
JDK27的LazyConstant
java·后端·java ee
知识搬运临时工4 小时前
加一层连接池,TPS 从 26438 掉到 12923
java·后端
琳少_4 小时前
java课堂笔记
java·开发语言·数据库·笔记
Helix2506 小时前
JDK安全编码实战:SQL注入、XSS、反序列化等10类漏洞防护完整指南|2026
java·安全·xss·sql注入·反序列化·安全编码·owasp
头发还在的女程序员6 小时前
家政小程序系统源码核销提交事务:多端操作怎样只确认一次服务结果
java·spring boot·源码·家政·核销事务
计算机–阿拉升学长6 小时前
基于SpringBoot的番茄种植水肥一体化管理系统 — 系统设计与实现
java·spring boot·后端·mysql·vue·javaweb
这个昵称不容易6 小时前
在线宠物用品交易网站设计与实现:SpringBoot 商城 158 个接口,附论文与运行截图
java·springboot·毕设