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--;
        }
    }
}
相关推荐
camellias_25 分钟前
【无标题】
java·tomcat
咸鱼2.041 分钟前
【java入门到放弃】需要背诵
java·开发语言
椰猫子1 小时前
Java:异常(exception)
java·开发语言
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
win x2 小时前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis
星晨雪海2 小时前
基于 @Resource 的支付 Service 多实现类完整示例
java·开发语言
阿维的博客日记2 小时前
什么是逃逸分析
java·juc
Ricky_Theseus3 小时前
C++右值引用
java·开发语言·c++
Rick19933 小时前
Java内存参数解析
java·开发语言·jvm
我是大猴子3 小时前
Spring代理类为何依赖注入失效?
java·后端·spring