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


相关推荐

  • Js判断数组中是否存在某个元素「建议收藏」

    Js判断数组中是否存在某个元素「建议收藏」方法一:indexOf(item,start);Item:要查找的值;start:可选的整数参数,缺省则从起始位子开始查找。indexOf();返回元素在数组中的位置,如果没有则返回-1;例子:vararr=[‘aaa’,’bbb’,’ccc’,’ddd’,’eee’];  vara=arr.indexOf(‘ddd’);  console.log(a);  //3  varb=arr.indexOf(‘d’);  console.log(b);  //-1  我通常的用法:if(

    2022年10月19日
    3
  • struts详细解释拦截器

    struts详细解释拦截器

    2022年1月5日
    43
  • opencv 人脸识别 (二)训练和识别

    opencv 人脸识别 (二)训练和识别上一篇中我们对训练数据做了一些预处理,检测出人脸并保存在\pic\color\x文件夹下(x=1,2,3,…类别号),本文做训练和识别。为了识别,首先将人脸训练数据转为灰度、对齐、归一化,再放入分类器(EigenFaceRecognizer),最后用训练出的model进行predict。—————————————–环境:vs2010+op

    2022年6月1日
    53
  • 原码,补码,二进制减法计算_二进制的原码和补码

    原码,补码,二进制减法计算_二进制的原码和补码这篇博客从一道题说起,已知x = (1<<31)-3,求x&-x?这里面考察了二进制的减法,减法也就牵涉了原码补码的一些概念。这里进行下梳理。 一。原码,补码概念1.原码就是早期用来表示数字的一种方式。一个正数,转换为二进制位就是这个正数的原码。负数的绝对值转换成二进制位然后在高位补1就是这个负数的原码例如:假设机器是32位系统,in…

    2022年9月25日
    2
  • 坑,MySQL中 order by 与 limit 混用,分页会出现问题!

    点击上方“全栈程序员社区”,星标公众号 重磅干货,第一时间送达 作者:丘八老爷 blog.csdn.net/qiubabin/article/details/70135556 在M…

    2021年6月28日
    74
  • Pytest(13)命令行参数–tb的使用

    Pytest(13)命令行参数–tb的使用前言pytest使用命令行执行用例的时候,有些用例执行失败的时候,屏幕上会出现一大堆的报错内容,不方便快速查看是哪些用例失败。–tb=style参数可以设置报错的时候回溯打印内容,可以设置参

    2022年7月31日
    6

发表回复

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

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