Convert BST to Greater Tree

MediumTreesbst

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary search tree with **distinct** values. Replace every node's value with the sum of its original value and all original values in the tree that are **greater** than it. Modify the tree in place (the shape does not change) and return its root; the grader serializes it in level order. An empty tree returns []. Visiting nodes from largest to smallest while keeping a running sum solves this in O(n).

Examples

Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
For example, 6 becomes 6 + 7 + 8 = 21 and 4 becomes 4 + 5 + 6 + 7 + 8 = 30.
Input: root = [0,null,1]
Output: [1,null,1]
1 has nothing greater; 0 becomes 0 + 1.

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^4 <= Node.val <= 10^4
  • All values are distinct and the input is a valid BST

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bst problems