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;
    }
}
相关推荐
独行soc7 分钟前
2025年渗透测试面试题总结- 某四字大厂面试复盘扩展 一面(题目+回答)
java·数据库·python·安全·面试·职场和发展·汽车
早上好啊! 树哥7 分钟前
常见的文件加密方式之【异或加密】,代入原理看例子,帮助更好的理解。
android·java·junit
记得早睡~12 分钟前
leetcode122-买卖股票的最佳时机II
javascript·数据结构·算法·leetcode
兰亭序咖啡44 分钟前
学透Spring Boot — 018. 优雅支持多种响应格式
java·spring boot·后端
小雨凉如水1 小时前
docker 常用命令
java·docker·eureka
高山流水&上善1 小时前
医药档案区块链系统
java·springboot
南汐以墨2 小时前
探秘JVM内部
java·jvm
Craaaayon2 小时前
Java八股文-List集合
java·开发语言·数据结构·list
信徒_2 小时前
Spring 怎么解决循环依赖问题?
java·后端·spring
2301_794461572 小时前
多线程编程中的锁策略
java·开发语言