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--;
        }
    }
}
相关推荐
Frostnova丶2 小时前
LeetCode 190.颠倒二进制位
java·算法·leetcode
闻哥3 小时前
Redis事务详解
java·数据库·spring boot·redis·缓存·面试
hrhcode3 小时前
【Netty】五.ByteBuf内存管理深度剖析
java·后端·spring·springboot·netty
道亦无名3 小时前
aiPbMgrSendAck
java·网络·数据库
发现你走远了3 小时前
Windows 下手动安装java JDK 21 并配置环境变量(详细记录)
java·开发语言·windows
心 -4 小时前
java八股文DI
java
json{shen:"jing"}4 小时前
字符串中的第一个唯一字符
算法·leetcode·职场和发展
黎雁·泠崖4 小时前
Java常用类核心详解(一):Math 类超细讲解
java·开发语言
大尚来也4 小时前
跨平台全局键盘监听实战:基于 JNativeHook 在 Java 中捕获 Linux 键盘事件
java·linux
追随者永远是胜利者4 小时前
(LeetCode-Hot100)15. 三数之和
java·算法·leetcode·职场和发展·go