Convert Sorted Array to Binary Search Tree
Practice this coding question on Coding Gurukul.
Problem statement
A library has unique accession numbers in increasing order. Its lookup service needs a balanced binary search tree so that searches do not follow a long chain. Your task Build a height-balanced binary search tree containing every input value exactly once. Important details For a deterministic tree, choose the lower middle element of every inclusive subarray as its root: mid = floor((left + right) / 2). Recursively build its left and right children from the remaining halves. A missing subtree has no node. Balance means that the heights of the two child subtrees differ by at most one at every node. Worked example For 2 4 6 8, the lower middle is 4. Its left child is 2; the right subtree has root 6 and right child 8. The serialization is 4 2 6 null null null 8.
Input format
First line: n. Second line: n strictly increasing integers.
Output format
Print the tree in breadth-first order, with null for missing children. Process left before right, enqueue children only for real nodes, and omit trailing null tokens.
Constraints
1 <= n <= 1000; -10000 <= values[i] <= 10000.
Sample input
4 2 4 6 8
Sample output
4 2 6 null null null 8
Sign in to run or submit a solution in C++, Java or Python.