[LeetCode] Binary Search Tree to Greater Sum Tree

1038. Binary Search Tree to Greater Sum 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
/**
* 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 {
TreeNode* helper(TreeNode* node, int& sum) {
if(!node) return nullptr;
helper(node->right, sum);
node->val = (sum += node->val);
helper(node->left, sum);
return node;
}
public:
TreeNode* bstToGst(TreeNode* root) {
int sum = 0;
return helper(root, sum);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/binary-search-tree-to-greater-sum-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.