Balance a Binary Search Tree In Place
Updated
Problem statement
Given the root of a binary search tree with distinct values, rebalance it in place using O(1) auxiliary space and return the new root.
Preserve every existing node and the in-order key sequence. Do not allocate an array, list, recursive call stack, or replacement tree nodes. One temporary sentinel node and a constant number of pointers are allowed.
Use the Day-Stout-Warren method: first rotate the tree into a sorted right vine. Let n be its node count, p the largest power of two at most n + 1, and leaves = n + 1 - p. Compress the first leaves vine links with left rotations, set n = n - leaves, then repeatedly set n = floor(n / 2) and compress that many links while n > 1. Return the sentinel's right child.
Function
balanceBstInPlace(root: TreeNode) → TreeNodeExamples
Example 1
root = [1,null,2,null,3,null,4,null,5]return = [4,2,5,1,3]The DSW steps turn the five-node right vine into a balanced tree rooted at 4.
Example 2
root = [5,4,null,3,null,2,null,1]return = [4,2,5,1,3]Right rotations first convert the left chain into the same sorted vine.
Example 3
root = [4,2,6,1,3,5,7]return = [4,2,6,1,3,5,7]The steps give back this tree, which is already perfectly balanced with seven nodes.
Constraints
- The tree contains from
0to50000nodes. -10^9 <= node.val <= 10^9.- All node values are distinct and the input satisfies the binary-search-tree invariant.
More Google Phone Screen questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Periodic-Color Binary Forest RootsPHONE SCREEN · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Tree Path GCDNewton School · PHONE SCREEN
- Light Source Hits: Sample, Compare, and FitOpenAI · PHONE SCREENOpenAI interview questions
- Random Forest Classifier from ScratchMicrosoft · PHONE SCREENMicrosoft interview questions
- Deterministic K-Means AssignmentsLyft · PHONE SCREENLyft interview questions
- Deterministic K-Means AssignmentsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Train a Binary Recommender MLPLinkedIn · PHONE SCREENLinkedIn interview questions
- Subtree Access OverridesPinterest · PHONE SCREENPinterest interview questions
- Scaled Dot-Product AttentionAmazon · PHONE SCREEN
- Implement K-Means ClusteringApple · PHONE SCREENApple interview questions
- Parking Fee CalculatorBreeze · PHONE SCREEN