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;
    }
}
相关推荐
Coder_Boy_2 分钟前
Deeplearning4j+ Spring Boot 电商用户复购预测案例中相关概念
java·人工智能·spring boot·后端·spring
css趣多多4 分钟前
add组件增删改的表单处理
java·服务器·前端
雨中飘荡的记忆6 分钟前
Spring Batch实战
java·spring
Java后端的Ai之路13 分钟前
【Spring全家桶】-一文弄懂Spring Cloud Gateway
java·后端·spring cloud·gateway
devmoon15 分钟前
在 Polkadot Runtime 中添加多个 Pallet 实例实战指南
java·开发语言·数据库·web3·区块链·波卡
野犬寒鸦18 分钟前
从零起步学习并发编程 || 第七章:ThreadLocal深层解析及常见问题解决方案
java·服务器·开发语言·jvm·后端·学习
云姜.22 分钟前
java抽象类和接口
java·开发语言
带刺的坐椅22 分钟前
Claude Code Skills,Google A2A Skills,Solon AI Skills 有什么区别?
java·ai·solon·a2a·claudecode·skills
爱学英语的程序员35 分钟前
面试官:你了解过哪些数据库?
java·数据库·spring boot·sql·mysql·mybatis
callJJ1 小时前
Spring AI 文本聊天模型完全指南:ChatModel 与 ChatClient
java·大数据·人工智能·spring·spring ai·聊天模型