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

没加的值为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
相加后再赋值,等于只了加一次

猜你喜欢

转载自www.cnblogs.com/immiao0319/p/12945138.html
今日推荐