
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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13 private int sum = 0;
14
15 public TreeNode BstToGst(TreeNode root) {
16 if (root != null) {
17 BstToGst(root.right);
18 sum += root.val;
19 root.val = sum;
20 BstToGst(root.left);
21 }
22 return root;
23 }
24}This C# solution maintains a class-level variable for the cumulative sum, processing each node during the reverse in-order traversal effectively to update their values.
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 Java solution provides a non-recursive way to handle the BST using a Stack, simulating reverse in-order traversal. Each node's value is computed iteratively based on aggregate sums.