538. Convert BST to Greater Tree (Easy)
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
Solution 1: Recursion 39ms
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int sum = 0;
public:
TreeNode* convertBST(TreeNode* root) {
if (!root) return NULL;
convertBST(root->right);
root->val += sum;
sum = root->val;
convertBST(root->left);
return root;
}
};
Solution 2: Iteration 42ms
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
TreeNode* node = root;
stack<TreeNode*> s;
int sum = 0;
while (node || !s.empty()) {
while (node) {
s.push(node);
node = node->right;
}
node = s.top(); s.pop();
node->val += sum;
sum = node->val;
node = node->left;
}
return root;
}
};