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;
    }
}
相关推荐
五月茶4 分钟前
Spring MVC
java·spring·mvc
sjsjsbbsbsn13 分钟前
Spring Boot定时任务原理
java·spring boot·后端
yqcoder14 分钟前
Express + MongoDB 实现在筛选时间段中用户名的模糊查询
java·前端·javascript
菜鸟蹦迪43 分钟前
八股文实战之JUC:ArrayList不安全性
java
2501_9032386543 分钟前
Spring MVC配置与自定义的深度解析
java·spring·mvc·个人开发
逻各斯1 小时前
redis中的Lua脚本,redis的事务机制
java·redis·lua
计算机毕设指导61 小时前
基于Springboot学生宿舍水电信息管理系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
计算机-秋大田1 小时前
基于Spring Boot的兴顺物流管理系统设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·spring·课程设计
计算机小白一个1 小时前
蓝桥杯 Java B 组之背包问题、最长递增子序列(LIS)
java·数据结构·蓝桥杯
二十雨辰2 小时前
[Java基础]网络编程
java·开发语言