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;
    }
}
相关推荐
L.EscaRC7 分钟前
Spring IOC核心原理与运用
java·spring·ioc
摇滚侠20 分钟前
2025最新 SpringCloud 教程,Nacos-总结,笔记19
java·笔记·spring cloud
在逃热干面24 分钟前
(笔记)获取终端输出保存到文件
java·笔记·spring
爱笑的眼睛1124 分钟前
深入理解MongoDB PyMongo API:从基础到高级实战
java·人工智能·python·ai
leoufung26 分钟前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode
笃行客从不躺平34 分钟前
遇到大SQL怎么处理
java·开发语言·数据库·sql
q***876041 分钟前
Spring Boot 整合 Keycloak
java·spring boot·后端
Billow_lamb42 分钟前
Spring Boot2.x.x全局拦截器
java·spring boot·后端
上不如老下不如小1 小时前
2025年第七届全国高校计算机能力挑战赛初赛 Java组 编程题汇总
java·计算机能力挑战赛
泉城老铁1 小时前
Springboot对接mqtt
java·spring boot·后端