[LeetCode] Convert BST to Greater Tree

538. Convert BST to Greater Tree

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.
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
/**
* 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 {
int sum = 0;
void sumHelper(TreeNode* node) {
if(!node) return;
sum += node->val;
sumHelper(node->left);
sumHelper(node->right);
}
void helper(TreeNode* node) {
if(!node) return;
helper(node->left);
int v = node->val;
node->val = sum;
sum -= v;
helper(node->right);
}
public:
TreeNode* convertBST(TreeNode* root) {
sumHelper(root);
helper(root);
return root;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/16/PS/LeetCode/convert-bst-to-greater-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.