FunctionRacerProblemsRace

Sorted Array to Binary Search Tree

EasyTreesPython, JavaScript, TypeScript, Java, C++

Build a binary search tree from the sorted list nums using this exact rule: the root is the middle item, and when the part has an even number of items the middle is the left one of the two (index (lo + hi) // 2). The left subtree is built the same way from the items before the middle, the right subtree from the items after it. Return the root. An empty list gives an empty tree.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

nums [1,2,3,4,5]
returns [3,1,4,null,2,null,5]

Root 3; left part [1,2] gives root 1 with right child 2; right part [4,5] gives root 4 with right child 5.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems