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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 在线词云制作生成 tagxedo

    在线词云制作生成 tagxedo在线词云制作生成tagxedo在线词云10行Python代码的词云待办在线词云原博文地址和详细使用方法介绍在线词云制作tagxedo在线网址http://www.tagxedo.com/注意点:直接访问http://www.tagxedo.com/app.html可能会超时,先进主页再点击右上角的create按钮进入创作页面会加载更快;需要下载一个软件,使用IE浏览器可加载上述软件,谷歌和EDGE实测都无法加载;导出的词云图片:10行Python代码的词云原博客地址:1

    2022年10月26日
  • tomcat7官网下载

    tomcat7官网下载1.官网地址:tomcat.apache.org,进入后点击Tomcat72.选择不同的类型,以“64-bitWindowszip”为例3.保存文件,确定4.解压后,进入bin目录,双击startup.bat,出现下图5.打开浏览器,输入127.0.0.1:8080,出现下图,安装成功转载于:https://my.oschina.net/u/4052883/blog/29915522…

    2022年5月19日
  • python 获取时间戳_datetime获取当前时间

    python 获取时间戳_datetime获取当前时间1、获取秒级、毫秒级和微秒级时间戳importtimeimportdatetimet=time.time()#当前时间print(t)#原始时间数据print(int(t))#秒级时间戳print(int(round(t*1000)))#毫秒级时间戳print(int(round(t*1000000)))#微秒级时间戳结果:1634191096.03610181634191096163419109603616341910960361

    2022年9月1日
  • 淘宝准点秒杀脚本

    淘宝准点秒杀脚本腾讯云服务器优惠购买链接:1核2G云服务器首年88元:http://url.cn/5Z0ZWGI准备软件下载地址:https://download.csdn.net/download/tangcv/11968538pycharm文件太大,不好上传,直接去官网下载:https://www.jetbrains.com/pycharm/download/#section=windo…

    2022年6月14日
  • sql 中文转拼音首字母

    sql 中文转拼音首字母

    2021年10月14日
  • 2021美赛A题解题思路(Fungi)

    2021美赛A题解题思路(Fungi)准时赴约。等待开题中……

    2022年4月28日

发表回复

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

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