Skip to content

538. Convert BST to Greater 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
class Solution {
 public:
  TreeNode* convertBST(TreeNode* root) {
    int prefix = 0;
    reversedInorder(root, prefix);
    return root;
  }

 private:
  void reversedInorder(TreeNode* root, int& prefix) {
    if (root == nullptr)
      return;

    reversedInorder(root->right, prefix);
    prefix += root->val;
    root->val = prefix;
    reversedInorder(root->left, prefix);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public TreeNode convertBST(TreeNode root) {
    reversedInorder(root);
    return root;
  }

  private int prefix = 0;

  private void reversedInorder(TreeNode root) {
    if (root == null)
      return;

    reversedInorder(root.right);
    prefix += root.val;
    root.val = prefix;
    reversedInorder(root.left);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def convertBST(self, root: TreeNode | None) -> TreeNode | None:
    prefix = 0

    def reversedInorder(root: TreeNode | None) -> None:
      nonlocal prefix
      if not root:
        return

      reversedInorder(root.right)
      prefix += root.val
      root.val = prefix
      reversedInorder(root.left)

    reversedInorder(root)
    return root