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--;
        }
    }
}
相关推荐
兆子龙11 分钟前
ahooks useMemoizedFn:解决 useCallback 的依赖地狱
java·javascript
曹牧5 小时前
BeanUtils.copyProperties‌
java
QWQ___qwq5 小时前
Java线程安全深度总结:基本类型与引用类型的本质区别
java·安全·面试
识君啊6 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
月月玩代码7 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
逆境不可逃8 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
阿珍爱上了阿强,在一个有星星的夜晚8 小时前
node后端页面性能监测分析
java·学习方法
Java程序之猿8 小时前
SpringBoot + camel+IBM MQ实现消息队列处理
java·spring boot·mybatis
z_鑫9 小时前
SpringCloud FeignClient 中 Bean 重复注册冲突解决方案解析
java·spring boot·spring cloud