Skip to content

1038. Binary Search Tree to Greater Sum Tree 👍

  • Time: $O(n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  TreeNode* bstToGst(TreeNode* root) {
    int prefix = 0;

    function<void(TreeNode*)> reversedInorder = [&](TreeNode* root) {
      if (root == nullptr)
        return;

      reversedInorder(root->right);

      root->val += prefix;
      prefix = root->val;

      reversedInorder(root->left);
    };

    reversedInorder(root);
    return root;
  }
};