Convert BST to Greater Tree

medium tree bst dfs

Problem

Convert a BST into a Greater Tree where every node's new value equals the sum of all original keys ≥ that node's key.

Inputtree = [4, 1, 6, 0, 2, 5, 7]
Output[22, 25, 13, 25, 24, 18, 7]
Sum of keys ≥ x for each x → e.g. for key 4: 4 + 5 + 6 + 7 = 22 (the node itself plus everything greater).

def convert_bst(root):
    s = 0

    def dfs(n):
        nonlocal s
        if not n:
            return
        dfs(n.right)
        s += n.val
        n.val = s
        dfs(n.left)

    dfs(root)
    return root
function convertBST(root) {
  let s = 0;
  function dfs(n) {
    if (!n) return;
    dfs(n.right);
    s += n.val;
    n.val = s;
    dfs(n.left);
  }
  dfs(root);
  return root;
}
class Solution {
    int s = 0;
    public TreeNode convertBST(TreeNode root) {
        dfs(root);
        return root;
    }
    private void dfs(TreeNode n) {
        if (n == null) return;
        dfs(n.right);
        s += n.val;
        n.val = s;
        dfs(n.left);
    }
}
TreeNode* convertBST(TreeNode* root) {
    int s = 0;
    function<void(TreeNode*)> dfs = [&](TreeNode* n) {
        if (!n) return;
        dfs(n->right);
        s += n->val;
        n->val = s;
        dfs(n->left);
    };
    dfs(root);
    return root;
}
Time: O(n) Space: O(h)