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--;
        }
    }
}
相关推荐
zander25810 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
骇客野人10 小时前
IntelliJ IDEA 菜单中英对照
java·ide·intellij-idea
我命由我1234510 小时前
Kotlin 面向对象 - 枚举排序
android·java·开发语言·java-ee·kotlin·android studio·android-studio
Sam_Deep_Thinking10 小时前
用Java 17从0到1写一个mini版RPC,理解远程调用的本质
java·面试·rpc·程序员·系统架构
yyds_yyd_1008611 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
敲代码的嘎仔11 小时前
从零搭建微服务:Spring Cloud Alibaba 全家桶踩坑实录(Nacos + OpenFeign + Gateway + Sentinel)
java·spring boot·spring·spring cloud·微服务·gateway·sentinel
一条泥憨鱼12 小时前
苍穹外卖【day7| 对购物车进行操作】
java·后端·mysql·苍穹外卖
lueluelue4719 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水1681 天前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
都叫我大帅哥1 天前
Java JJWT 完全指南:从入门到生产级实践
java