Description
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 the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- Both the left and right subtrees must also be binary search trees.
Solution
From the BST’s constraints:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- We know that the current node’s new value will be sum of left subtree + current node’s value.
- The sum of left subtree + the current node needs to be passed down to the right subtree. A leaf node’s sum will be the sum passed down from it’s parent + the value of itself.
- The left most node of the a subtree will contain the sum of the whole subtree, which needs to be returned to process other subproblems.
And there, we could write a recursion from the bullet points above.
Implementation
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int runner(TreeNode* root, int sum) {
if (!root) return sum;
int right = runner(root->right, sum);
root->val += right;
int left = runner(root->left, root->val);
return left;
}
TreeNode* convertBST(TreeNode* root) {
runner(root, 0);
return root;
}
};