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--;
        }
    }
}
相关推荐
wb043072017 分钟前
使用 Java 开发 MCP 服务并发布到 Maven 中央仓库完整指南
java·开发语言·spring boot·ai·maven
Rsun045518 分钟前
设计模式应该怎么学
java·开发语言·设计模式
5系暗夜孤魂31 分钟前
系统越复杂,越需要“边界感”:从 Java 体系理解大型工程的可维护性本质
java·开发语言
二月夜44 分钟前
Spring循环依赖深度解析:从三级缓存原理到跨环境“灵异”现象
java·spring
nbwenren1 小时前
Springboot中SLF4J详解
java·spring boot·后端
wellc2 小时前
java进阶知识点
java·开发语言
灰色小旋风2 小时前
力扣合并K个升序链表C++
java·开发语言
_MyFavorite_2 小时前
JAVA重点基础、进阶知识及易错点总结(28)接口默认方法与静态方法
java·开发语言·windows
Kk.08022 小时前
力扣 LCR 084.全排列||
算法·leetcode·职场和发展
旖-旎2 小时前
分治(快速选择算法)(3)
c++·算法·leetcode·排序算法·快速选择