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 小时前
LeetCode1281~1300题目解析
java·leetcode
missile1112 小时前
# HDR 算法 ISP 通路客制化方案(G100 / mt6789)
java·前端·javascript
全栈陈序员2 小时前
【Python】基础语法入门(三十三)—— 日志系统详解:用 logging 记录程序运行
java·开发语言·python
她的男孩2 小时前
低代码加字段后表结构怎么同步:预览安全 DDL,高风险变更再强制执行
java·spring boot·低代码
简简单单就是我_hehe2 小时前
一次 ClickHouse 服务器磁盘告警的排查与修复实录
java·服务器·前端
Thomas.Sir2 小时前
第11课:文件上传下载、跨域CORS配置,SpringBoot4.x跨域新方案
java·spring boot
wuminyu2 小时前
JVM规范学习总结:class执行性能差异
java·linux·c语言·jvm·c++
一条泥憨鱼3 小时前
【RabbitMQ】高级篇
java·分布式·rabbitmq·php·ruby
京师20万禁军教头3 小时前
50-常用类-Arrays
java
寰梦3 小时前
Spring Boot + MinIO 大文件上传完整实战:MD5 秒传、分片上传、断点续传与引用一致性
java·spring boot·文件上传·minio