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--;
        }
    }
}
相关推荐
Knight_AL1 小时前
深入理解 ForkJoinPool、parallelStream、CompletableFuture:从原理到生产最佳实践(含百万订单统计实战)
java
王五周八2 小时前
玩转 Spring AI Agent:基于 SpringBoot 集成 AI 工具与 Skills 能力实践
java·spring
小锋java12342 小时前
【技术专题】LangChain4j 开发Java Agent智能体 - 会话记忆
java·人工智能
计算机安禾2 小时前
【算法分析与设计】第43篇:空间复杂度类与Savitch定理
java·服务器·网络·数据库·算法
圣保罗的大教堂2 小时前
leetcode 3751. 范围内总波动值 I 中等
leetcode
JAVA社区2 小时前
Java高级全套教程(十四)—— SpringData超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
Java爱好狂.2 小时前
Java高并发系统架构设计核心技术开源!
java·高并发·并发编程·java面试·java面试题·java程序员·java八股文
武子康2 小时前
Java-16 深入浅出MyBatis 架构设计与源码剖析:从初始化到 SQL 执行全流程
java·后端
8Qi82 小时前
LeetCode 416:分割等和子集 —— (0-1背包)
java·算法·leetcode·动态规划·背包问题·01背包