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


相关推荐

  • linux vim中取消底色

    linux vim中取消底色

    2022年2月23日
    70
  • nginx 转发websocket_nginx配置websocket

    nginx 转发websocket_nginx配置websocketnginx入门之简易,相信用过的同学都会有体会,没有复杂安装,没有庞大的配置文件,在nginx.conf配置一下,就可以提供不同类型的服务。本文简单描述下如何转发(反向代理)一个socket服务。将要配置一个如上图示的转发服务。在nginx.conf文件,与events平行的级别,配置一个stream#evnets是配置文件已有内容events{ worker_connec…

    2022年10月9日
    4
  • c++char和int转换_int转换为char数组

    c++char和int转换_int转换为char数组int转char类型

    2022年10月21日
    5
  • 如果要学习web前端开发,需要学习什么?

    如果要学习web前端开发,需要学习什么?遇到很多新手,都会问,如果要学习web前端开发,需要学习什么?难不难?多久能入门?怎么能快速建一个网站?工资能拿到多少?还有些让我推荐一些培训机构什么的要去学习。我建议是自学,实在是觉得自己没有这个能

    2022年8月6日
    6
  • dns bind 配置_dns forwarding设置

    dns bind 配置_dns forwarding设置智能dns配置基于bind9视图语句语法viewview_name[class]{match-clients{address_match_list};match-destinations{address_match_list};match-recursive-only{yes_or_no};[view_option;…][zone-statisti…

    2025年7月16日
    5
  • 系统结构-并行算法FORK JOIN[通俗易懂]

    系统结构-并行算法FORK JOIN[通俗易懂]并行算法FORKJOIN一、FORKJOIN定义二、举例题目分析:一、FORKJOIN定义FORK语句的形式:FORKm,其中m为新进程开始的标号。执行FORKm语句时,派生出标号为m开始的新进程,具体为:1、准备好这个新进程启动和执行所必需的信息;2、如果是共享主存,则产生存储器指针、映像函数和访问权数据;3、将空闲的处理机分配给派生的新进程,如果没有空闲处理机,则让它们排队等待;4、继续在原处理机上执行FORK语句的原进程。与FORK语句相配合,作为每个并发进程的终端语句J

    2026年1月31日
    5

发表回复

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

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