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--;
        }
    }
}
相关推荐
步菲1 分钟前
springboot canche 无法避免Null key错误, Null key returned for cache operation
java·开发语言·spring boot
毕设源码-朱学姐10 分钟前
【开题答辩全过程】以 基于SpringBoot的中医理疗就诊系统为例,包含答辩的问题和答案
java·spring boot·后端
2201_757830874 小时前
全局异常处理器
java
小徐Chao努力5 小时前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
Coder_Boy_5 小时前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain
Coder_Boy_6 小时前
基于SpringAI的智能平台基座开发-(六)
java·数据库·人工智能·spring·langchain·langchain4j
长安er7 小时前
LeetCode136/169/75/31/287 算法技巧题核心笔记
数据结构·算法·leetcode·链表·双指针
伯明翰java7 小时前
Java数据类型与变量
java·开发语言
想用offer打牌7 小时前
如何开启第一次开源贡献之路?
java·后端·面试·开源·github
小许学java7 小时前
Spring原理
java·spring·生命周期·作用域·原理