Binary Search Tree to Greater Sum Tree

medium binary search tree reverse inorder dfs

Problem

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is replaced with the original key plus the sum of all keys greater than the original key. Because it is a BST, a reverse in-order traversal (right, node, left) visits keys from largest to smallest, so a single running total lets us update each node in place.

Inputnums = [2, 1, 3] (level order, builds BST root 2)
Output[5, 6, 3]
Largest key 3 stays 3; key 2 becomes 2 + 3 = 5; key 1 becomes 1 + 5 = 6.

def bstToGst(root):
    acc = 0
    def dfs(node):
        nonlocal acc
        if not node:
            return
        dfs(node.right)
        acc += node.val
        node.val = acc
        dfs(node.left)
    dfs(root)
    return root
function bstToGst(root) {
  let acc = 0;
  function dfs(node) {
    if (!node) return;
    dfs(node.right);
    acc += node.val;
    node.val = acc;
    dfs(node.left);
  }
  dfs(root);
  return root;
}
class Solution {
    private int acc = 0;
    public TreeNode bstToGst(TreeNode node) {
        if (node == null) return node;
        bstToGst(node.right);
        acc += node.val;
        node.val = acc;
        bstToGst(node.left);
        return node;
    }
}
class Solution {
    int acc = 0;
public:
    TreeNode* bstToGst(TreeNode* node) {
        if (node == nullptr) return node;
        bstToGst(node->right);
        acc += node->val;
        node->val = acc;
        bstToGst(node->left);
        return node;
    }
};
Time: O(n) Space: O(h)