
Sponsored
Sponsored
A reverse in-order traversal (right-root-left) allows us to visit nodes in decreasing order of their values in a BST. By maintaining a cumulative sum during this traversal, we can update each node with the sum of all nodes that have been visited so far, effectively converting it into a Greater Sum Tree.
The time complexity is O(n) where n is the number of nodes, as each node is visited once. The space complexity is O(h), where h is the height of the tree, representing the stack space used by the recursion.
1#include<stdio.h>
2
3struct TreeNode {
4 int val;
5 struct TreeNode *left;
6 struct TreeNode *right;
7};
8
9void transform(struct TreeNode* node, int* sum) {
10 if (node == NULL) return;
11 transform(node->right, sum);
12 *sum += node->val;
13 node->val = *sum;
14 transform(node->left, sum);
15}
16
17struct TreeNode* bstToGst(struct TreeNode* root) {
18 int sum = 0;
19 transform(root, &sum);
20 return root;
21}This C solution uses a helper function to perform reverse in-order traversal on the BST. As it visits each node, it maintains a cumulative sum of values, updating each node with this cumulative sum. This effectively transforms the BST into a Greater Sum Tree.
We can emulate the recursive reverse in-order traversal with an iterative approach using a stack. By processing the nodes in decreasing order of their values, we maintain a sum of all visited nodes and update each node accordingly.
The time complexity is O(n) because each node is visited once in the traversal loop. Space complexity is O(h) for stack use in the case where the tree's height is h.
1
This C solution uses an explicit stack data structure to simulate the recursive reverse in-order traversal process. The sum is accumulated for nodes observed, and their values are updated iteratively.