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;
    }
}
相关推荐
阿杆.14 小时前
如何在 Spring Boot 中接入 Amazon ElastiCache
java·spring boot·后端
别惹CC14 小时前
Spring AI 进阶之路04:集成 SearXNG 实现联网搜索
java·后端·spring
资深web全栈开发14 小时前
LeetCode 3573. 买卖股票的最佳时机 V - 动态规划解法详解
算法·leetcode·动态规划
invicinble14 小时前
springboot的日志体系
java·spring boot·后端
Chen--Xing14 小时前
LeetCode LCR 119.最长连续序列
c++·python·算法·leetcode·rust
czlczl2002092514 小时前
拒绝 DTO 爆炸:详解 Spring Boot 参数校验中的“分组校验” (Validation Groups) 技巧
java·spring boot·后端
悟空码字14 小时前
SpringBoot动态脱敏实战,从注解到AOP的优雅打码术
java·后端
摆烂z14 小时前
maven中打包不打全部包+多线程打包
java·开发语言·maven
嘟嘟w14 小时前
什么是Token,Token和Session以及Cookie的区别
java
小鸡脚来咯14 小时前
springboot项目包结构
java·spring boot·后端