
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.
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode(int x) { val = x; }
6}
7
8class Solution {
9 private void transform(TreeNode node, int[] sum) {
10 if (node == null) return;
11 transform(node.right, sum);
12 sum[0] += node.val;
13 node.val = sum[0];
14 transform(node.left, sum);
15 }
16
17 public TreeNode bstToGst(TreeNode root) {
18 int[] sum = new int[1];
19 transform(root, sum);
20 return root;
21 }
22}This Java solution uses an array to maintain a mutable reference of the cumulative sum. The reverse in-order traversal updates each node, similarly transforming the BST to 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
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.