LeetCode – 538. Convert BST to Greater Tree

LeetCode – 538. Convert BST to Greater Tree

大家好,又见面了,我是全栈君。

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
              5
            /   \
           2     13

Output: The root of a Greater Tree like this:
             18
            /   \
          20     13

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root == null)
            return null;
        
        convert(root);
        return root;
    }
    
    public void convert(TreeNode root) {
        if (root == null)
            return ;
        convert(root.right);
        root.val += sum;
        sum = root.val;
        convert(root.left);
    }
    
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/108253.html原文链接:https://javaforall.net

(0)
上一篇 2022年3月6日 上午6:00
下一篇 2022年3月6日 上午6:00


相关推荐

  • 白化Whitening

    白化Whitening白化操作的目的是让我们的减少冗余信息 准确来说通过白化操作我们有两个目的 每个特征之间关联性更少每个特征有相同的方差对于第一个目的来说 我们可以通过熟悉的 PCA 来实现 PCAPrincipal PCA 是一个用来减少特征纬度的算法 它通过减少特征的纬度来减少冗余信息 比如说 下图所示的一个特征纬度为 2 的点分类问题 我们可以看到数据的主要

    2026年3月18日
    2
  • List中删除指定元素

    List中删除指定元素第一种 ArrayList lt Integer gt list newArrayList lt Integer gt list add 2 list add 3 list add 1 for inti 0 i lt list size i if l

    2026年3月17日
    1
  • LVS基本配置

    LVS基本配置LVS说明【Linux操作系统核心空间中、一般采用DR构建集群】小结:{Ipvsadm:管理集群服务的命令行工具、Ipvs:内核模块/代码;三种负载均衡模式:【NAT:修改IP、双网卡,RIP指向DIP内网网关、任意操作系统】、【DR直接路由:一个网卡、配置别名、DIP和RIP在同一网关上、修改MAC地址】、【TUP隧道:封装IP报文,异地服务连接】} LVS主要组成部分为:  负

    2022年7月23日
    9
  • C#中string.format用法详解「建议收藏」

    C#中string.format用法详解「建议收藏」string.Format对C#字符串格式化String.Format方法的几种定义:String.Format(String,Object)将指定的String中的格式项替换为指定的

    2022年7月3日
    19
  • pcharm激活码_通用破解码

    pcharm激活码_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月16日
    70
  • 关于cfg80211

    关于cfg80211转至 http blog csdn net robertsong20 article details 关于 cfg80211cfg8 是 Linux802 11 配置 API cfg80211 用于取代 Wireless Extensions nl80211 用来配置一个 cfg80211 设备 用于内核用户空间之间的通信 Wi

    2026年3月17日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号