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--;
        }
    }
}
相关推荐
captain3765 分钟前
创建多线程程序
java·java-ee
野蛮人6号6 分钟前
黑马天机学堂Day01-08.搭建项目环境-本地开发部署方式——不知道nacos的密码是什么
java·spring cloud·黑马程序员·天机学堂·黑马天机学堂
Roy_Sashulin7 分钟前
灵杉Java编程平台第一章:安装
java·开发语言
plainGeekDev1 小时前
synchronized → Coroutines
android·java·kotlin
Lyra_Infra1 小时前
故障排查报告:Spring boot连接 Nacos 异常及启动失败
java·spring boot
liguojun20251 小时前
智慧文体旅系统选哪家?豆米跳跳十年技术沉淀支持源码交付
java·大数据·人工智能·物联网·1024程序员节
hold?fish:palm1 小时前
7 接雨水
开发语言·c++·leetcode
学习使得吾快乐2 小时前
时序数据库 TDengine 在设备监测中的实际落地:从传感器上报到实时看板
java·时序数据库·tdenginne
程序员清风2 小时前
推荐几个我常听的AI播客!
java·后端·面试
唐青枫2 小时前
Java Gradle 实战指南:从 Wrapper、Kotlin DSL 到 Spring Boot 多模块构建
java·kotlin·gradle