
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.
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val)
3 this.left = (left===undefined ? null : left)
4 this.right = (right===undefined ? null : right)
5}
6
7var bstToGst = function(root) {
8 let sum = 0;
9 const transform = (node) => {
10 if (node === null) return;
11 transform(node.right);
12 sum += node.val;
13 node.val = sum;
14 transform(node.left);
15 };
16 transform(root);
17 return root;
18};This JavaScript solution leverages a closure for the cumulative sum, updating each node's value through a reverse in-order traversal to achieve the transformation.
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.
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public TreeNode BstToGst(TreeNode root) {
var stack = new Stack<TreeNode>();
var node = root;
int sum = 0;
while (stack.Count > 0 || node != null) {
while (node != null) {
stack.Push(node);
node = node.right;
}
node = stack.Pop();
sum += node.val;
node.val = sum;
node = node.left;
}
return root;
}
}This C# iterative solution enables visiting nodes with a Stack, supporting computation of sums and updating values with less reliance on recursive depth of function.