|
| 1 | +#Convert BST to Greater Tree |
| 2 | +###Problem link:[Click me](https://leetcode.com/problems/convert-bst-to-greater-tree/) |
| 3 | +--- |
| 4 | + |
| 5 | +-##Question: |
| 6 | +>Given the root of 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 |
| 7 | + the sum of all keys greater than the original key in BST. |
| 8 | +>>Example : |
| 9 | +
|
| 10 | + 4 |
| 11 | +
|
| 12 | + / \ |
| 13 | +
|
| 14 | + 1 6 |
| 15 | +
|
| 16 | + / \ / \ |
| 17 | +
|
| 18 | + 0 2 5 7 |
| 19 | +
|
| 20 | + \ \ |
| 21 | +
|
| 22 | + 3 8 |
| 23 | +
|
| 24 | +
|
| 25 | + Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] |
| 26 | + Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] |
| 27 | +
|
| 28 | +--- |
| 29 | + |
| 30 | +-##Solution: |
| 31 | +**Code :** |
| 32 | + |
| 33 | +```cpp |
| 34 | +/** |
| 35 | + * Definition for a binary tree node. |
| 36 | + * struct TreeNode { |
| 37 | + * int val; |
| 38 | + * TreeNode *left; |
| 39 | + * TreeNode *right; |
| 40 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 41 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 42 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 43 | + * }; |
| 44 | +*/ |
| 45 | +classSolution { |
| 46 | +public: |
| 47 | + TreeNode* convertBST(TreeNode* root) { |
| 48 | + int cur_sum = 0; |
| 49 | + convertBSTHelper(root, &cur_sum); |
| 50 | + return root; |
| 51 | + } |
| 52 | + |
| 53 | +private: |
| 54 | + void convertBSTHelper(TreeNode* root, int*cur_sum) { |
| 55 | + if (!root) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + if (root->right) { |
| 60 | + convertBSTHelper(root->right, cur_sum); |
| 61 | + } |
| 62 | + root->val = (*cur_sum += root->val); |
| 63 | +if (root->left) { |
| 64 | +convertBSTHelper(root->left, cur_sum); |
| 65 | + } |
| 66 | + } |
| 67 | +}; |
| 68 | +``` |
| 69 | + |
| 70 | +**Time Complexity : O(n)** |
| 71 | + |
| 72 | +--- |
| 73 | + |
| 74 | +Reference :[Dev to](https://dev.to/) |
| 75 | + |
| 76 | + |