forked from azl397985856/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
538.convert-bst-to-greater-tree.js
61 lines (56 loc) · 1.17 KB
/
538.convert-bst-to-greater-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* @lc app=leetcode id=538 lang=javascript
*
* [538] Convert BST to Greater Tree
*
* https://leetcode.com/problems/convert-bst-to-greater-tree/description/
*
* algorithms
* Easy (50.04%)
* Total Accepted: 75.4K
* Total Submissions: 149K
* Testcase Example: '[5,2,13]'
*
* 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.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var convertBST = function(root) {
let res = 0;
function r(root) {
if (root === null) return null;
r(root.right);
root.val += res;
res = +root.val;
r(root.left);
return root;
}
r(root);
return root;
};