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--;
        }
    }
}
相关推荐
dishugj7 分钟前
HANA数据库常用命令总结
java·前端·数据库
khalil10209 分钟前
代码随想录算法训练营Day-48 单调栈02 | 42. 接雨水、84.柱状图中最大的矩形
数据结构·c++·算法·leetcode·单调栈·接雨水
MacroZheng9 分钟前
横空出世!IDEA最强MyBatis插件来了,功能很全!
java·后端·mybatis
zhangjw3414 分钟前
第9篇:Java集合框架入门,List详解:ArrayList与LinkedList底层彻底吃透
java·开发语言·list
大大杰哥15 分钟前
Java集合框架(List/Set/Queue)核心总结与代码示例
java·数据结构
深蓝轨迹16 分钟前
RedisTemplate 核心操作API汇总(Spring Data Redis)
java·redis·spring
大大杰哥21 分钟前
leetcode hot100(3)子串
c++·算法·leetcode
Cat_Rocky22 分钟前
K8s RBAC认证 简单讲
java·docker·kubernetes
一只IT攻城狮23 分钟前
️ Spring Boot 文件上传,防御恶意文件攻击
java·spring boot·web安全
ch.ju31 分钟前
Java Programming Chapter 3——Subscript of the array
java·开发语言