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--;
        }
    }
}
相关推荐
24k小善几秒前
FlinkUpsertKafka深度解析
java·大数据·flink·云计算
EnigmaCoder20 分钟前
java面向对象编程【高级篇】之多态
java·开发语言
秋名RG25 分钟前
浅谈Java 内存管理:栈与堆,垃圾回收
java·开发语言·jvm
编程绿豆侠25 分钟前
力扣HOT100之链表:23. 合并 K 个升序链表
算法·leetcode·链表
WMSmile1 小时前
Maven下载aspose依赖失败的解决方法
java·maven
Python私教1 小时前
Rust:安全与性能兼得的现代系统编程语言
java·安全·rust
2401_897930061 小时前
Maven 使用教程
java·maven
PXM的算法星球1 小时前
【Java后端】MyBatis 与 MyBatis-Plus 如何防止 SQL 注入?从原理到实战
java·sql·mybatis
zh_xuan1 小时前
java Optional
java·开发语言
阿杜杜不是阿木木1 小时前
03.使用spring-ai玩转MCP
java·人工智能·spring boot·spring·mcp·spring-ai