Java | Leetcode Java题解之第538题把二叉搜索树转换为累加树

题目:

题解:

java 复制代码
class Solution {
    public TreeNode convertBST(TreeNode root) {
        int sum = 0;
        TreeNode node = root;

        while (node != null) {
            if (node.right == null) {
                sum += node.val;
                node.val = sum;
                node = node.left;
            } else {
                TreeNode succ = getSuccessor(node);
                if (succ.left == null) {
                    succ.left = node;
                    node = node.right;
                } else {
                    succ.left = null;
                    sum += node.val;
                    node.val = sum;
                    node = node.left;
                }
            }
        }

        return root;
    }

    public TreeNode getSuccessor(TreeNode node) {
        TreeNode succ = node.right;
        while (succ.left != null && succ.left != node) {
            succ = succ.left;
        }
        return succ;
    }
}
相关推荐
盖世英雄酱5813629 分钟前
Read timed out问题 排查
java·数据库·后端
狼爷42 分钟前
破解 JetBrains 的学生,后来都成了它的 “推销员”:一场用习惯换市场的长期战
java·jetbrains
.豆鲨包1 小时前
【Android】Viewpager2实现无限轮播图
android·java
BXCQ_xuan1 小时前
软件工程实践二:Spring Boot 知识回顾
java·spring boot·后端
老赵的博客1 小时前
c++ unqiue指针
java·jvm·c++
wuxuanok1 小时前
SpringBoot -原理篇
java·spring boot·spring
柿蒂2 小时前
从if-else和switch,聊聊“八股“的作用
android·java·kotlin
二饭2 小时前
Spring Boot 项目启动报错:MongoSocketOpenException 连接被拒绝排查日记
java·spring boot·后端
懒虫虫~2 小时前
通过内存去重替换SQL中distinct,优化SQL查询效率
java·sql·慢sql治理
鼠鼠我捏,要死了捏2 小时前
基于Redisson的分布式锁原理深度解析与性能优化实践指南
java·高并发·redisson