|
| 1 | +/* |
| 2 | +Convert BST to Greater Tree |
| 3 | +=========================== |
| 4 | +
|
| 5 | +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 sum of all keys greater than the original key in BST. |
| 6 | +
|
| 7 | +As a reminder, a binary search tree is a tree that satisfies these constraints: |
| 8 | +
|
| 9 | +The left subtree of a node contains only nodes with keys less than the node's key. |
| 10 | +The right subtree of a node contains only nodes with keys greater than the node's key. |
| 11 | +Both the left and right subtrees must also be binary search trees. |
| 12 | +Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ |
| 13 | +
|
| 14 | +Example 1: |
| 15 | +Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] |
| 16 | +Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] |
| 17 | +
|
| 18 | +Example 2: |
| 19 | +Input: root = [0,null,1] |
| 20 | +Output: [1,null,1] |
| 21 | +
|
| 22 | +Example 3: |
| 23 | +Input: root = [1,0,2] |
| 24 | +Output: [3,3,2] |
| 25 | +
|
| 26 | +Example 4: |
| 27 | +Input: root = [3,2,4,1] |
| 28 | +Output: [7,9,4,10] |
| 29 | +
|
| 30 | +Constraints: |
| 31 | +The number of nodes in the tree is in the range [0, 104]. |
| 32 | +-104 <= Node.val <= 104 |
| 33 | +All the values in the tree are unique. |
| 34 | +root is guaranteed to be a valid binary search tree. |
| 35 | +*/ |
| 36 | + |
| 37 | +/** |
| 38 | + * Definition for a binary tree node. |
| 39 | + * struct TreeNode { |
| 40 | + * int val; |
| 41 | + * TreeNode *left; |
| 42 | + * TreeNode *right; |
| 43 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 44 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 45 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 46 | + * }; |
| 47 | + */ |
| 48 | + |
| 49 | +class Solution |
| 50 | +{ |
| 51 | +public: |
| 52 | + void rev_inorder(TreeNode *node, int &sum) |
| 53 | + { |
| 54 | + if (!node) |
| 55 | + return; |
| 56 | + rev_inorder(node->right, sum); |
| 57 | + node->val += sum; |
| 58 | + sum = node->val; |
| 59 | + rev_inorder(node->left, sum); |
| 60 | + } |
| 61 | + |
| 62 | + TreeNode *convertBST(TreeNode *root) |
| 63 | + { |
| 64 | + int sum = 0; |
| 65 | + rev_inorder(root, sum); |
| 66 | + return root; |
| 67 | + } |
| 68 | +}; |
0 commit comments