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--;
        }
    }
}
相关推荐
markinmarkin1 天前
Spring 中Bean 的作用域有哪些?
java·后端·spring
山荷枝1 天前
Java学习第十天
java·学习
matlabgoodboy1 天前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计
hanlin031 天前
动态规划专练:力扣第121、122题
笔记·算法·leetcode
To_OC1 天前
LC 74 搜索二维矩阵:换皮的二分查找,我居然一开始没看出来
javascript·算法·leetcode
玖玥拾1 天前
LeetCode 189 轮转数组
算法·leetcode
程序员雷欧1 天前
环形缓冲区深度解析:从基础原理到Disruptor源码的全面剖析
java
xiaoqiMikko1 天前
Dependabot 面板全绿,不代表你的 Tomcat 没洞
java·spring boot
前端开发张小七1 天前
Java 学习笔记 · 第三课:多线程与并发编程(线程、同步、死锁、Lock、乐观锁与悲观锁)
java·后端·程序员
花生了什么事o1 天前
JVM 垃圾回收:对象如何被判定和回收
java·jvm