538. Convert BST to Greater Tree 538.将BST转换为更大的树

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

思路问题:

helper中序递增,什么也不做,就返回一个数组。
然后主函数里面不就是最一般的情况了吗?大于等于它的就加上。
那这样,主函数里面就要再遍历一遍

新的思路:helper中序里面可以直接加、做一些别的处理。似乎更合理。
主函数就不用遍历两次了。


没加的值为sum = 13 sum = root.val; 13 
加和后的值为root.val = 26.root.val += sum;两个13相加了。
root.val本来就有值,此时同一个值加了两次,被自己覆盖了。反正不能加新值就对了。
赋值后再加新值,等于加了两次
没加的值为sum = 5
加和后的值为root.val = 10
没加的值为sum = 2
加和后的值为root.val = 4
这么写有bug
加和后的值为root.val =  root.val += sum;就是本身,root本身没有值
没加的值为sum = 13
加和后的值为root.val = 18 5加上了13
没加的值为sum = 18 
加和后的值为root.val = 20
没加的值为sum = 20
写是这么写,初始化是从sum开始的。第一步并没有加。
这么写没bug
相加后再赋值,等于只了加一次

 

特殊情况必须先写上,实在是怕忘。其实提醒自己一下也不难对吧。

//root.val += sum; sum = root.val; 好吧应该用这种方式来直接给节点赋值

应该是root加上sum的值,root.val += sum;不是反过来

这道题的特殊之处是先右边,中间再左边

root.left = convertBST(root.left); 有没有左边好像没有影响

class Solution {
    int sum = 0;
    
    public TreeNode convertBST(TreeNode root) {
        //特殊情况必须先写上,实在是怕忘
        if (root == null) 
            return null;
        
        convertBST(root.right);
        
        root.val += sum;
        sum = root.val;
        
        convertBST(root.left);
        
        return root;
    }
}
View Code

 

原文地址:https://www.cnblogs.com/immiao0319/p/12945138.html