We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy trees problem, graded against 6 test cases (3 of them hidden).
Recursive traversal of binary trees and BSTs - depth, validation, and path problems.
Reach for it when you see: A TreeNode input, or anything about depth, ancestry, or in-order ordering.
More Treesproblems →Balance is about subtree sizes, and a sorted array hands you the split point for free: choosing the middle element as the root puts exactly half the remaining values on each side, so the two subtrees differ in size by at most one. Recursing gives a tree of height O(log n) by construction - no rotations, no rebalancing.
The BST ordering is automatic too, since everything left of the midpoint is smaller and everything right is larger. That is the same invariant binary search exploits, used in the opposite direction.
Emitting preorder (root, then left, then right) makes the recursion and the output line up exactly: append the midpoint, then recurse left, then recurse right. Nothing needs to be assembled afterwards.
The reason the problem pins down the even-length tie-break is that any midpoint choice yields a valid balanced BST, so the answer would otherwise not be unique - a real issue for automated checking, and a good thing to clarify in an interview before writing code.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.