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 分钟前
Java 面试 100 题深度解析 · 专栏总览与大纲
java·面试
银迢迢4 分钟前
idea控制台中文乱码采用好几种方法一直解决不了
java·ide·intellij-idea
悦悦子a啊5 分钟前
将学生管理系统改造为C/S模式 - 开发过程报告
java·开发语言·算法
步步为营DotNet13 分钟前
深度解析C# 11的Required成员:编译期验证保障数据完整性
java·前端·c#
han_hanker26 分钟前
泛型的基本语法
java·开发语言
vx_bisheyuange1 小时前
基于SpringBoot的社区养老服务系统
java·spring boot·后端·毕业设计
廋到被风吹走1 小时前
【Java】Exception 异常体系解析 从原理到实践
java·开发语言
谷哥的小弟1 小时前
Spring Framework源码解析——GenericTypeResolver
java·spring·源码
sheji34161 小时前
【开题答辩全过程】以 基于Springboot的超市仓库管理系统设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
我命由我123451 小时前
Android 开发问题:在无法直接获取或者通过传递获取 Context 的地方如何获取 Context
android·java·java-ee·android studio·android jetpack·android-studio·android runtime