Advertisement
1038. Binary Search Tree to Greater Sum Tree
MediumView on LeetCode
Time: O(n)
Space: O(n)
Approach
Reverse in-order traversal (right → node → left); accumulate a running prefix sum and assign it to each node.
1038.cs
C#
// Approach: Reverse in-order traversal (right → node → left); accumulate a running prefix sum and assign it to each node.
// Time: O(n) Space: O(n)
public class Solution
{
int prefix = 0;
public TreeNode BstToGst(TreeNode root)
{
if (root.right != null)
BstToGst(root.right);
prefix += root.val;
root.val = prefix;
if (root.left != null)
BstToGst(root.left);
return root;
}
}Advertisement
Was this solution helpful?