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--;
        }
    }
}
相关推荐
顧棟1 小时前
【ES实战】 索引模板「可追溯、可校验」:一种模板治理的工程化思路
java·数据库·elasticsearch
玄昌盛不会编程2 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊2 小时前
LeetCode3061~3080题目解析
java·leetcode
装不满的克莱因瓶3 小时前
【AI时代必学】一篇文章教会你从零搭建Serverless架构
java·人工智能·ai·云原生·架构·serverless
七夜zippoe4 小时前
多轮对话管理:Session/记忆在 Java 后端怎么存(存储设计实战)
java·开发语言·ai·session·记忆
杨凯凡4 小时前
Spring Boot 事务提交后消息仍会丢?TransactionalEventListener 与 Outbox 可靠投递实战
java·spring boot
Java后端的Ai之路5 小时前
Java并发编程22-Lock接口
java·人工智能·prompt·lock
文丑颜不良啊5 小时前
LeetCode3081~3100题目解析
java·leetcode
SimonKing5 小时前
快讯!local-notes素笺笔记又又又更新了!
java·后端·程序员
Rain的Java大神之路5 小时前
面试官:设计一个自动售货机系统。我:别急着写代码,先问5个问题|状态机+防超卖+断电自愈,一套答法讲透
java·后端·面试