Given a level order representation of a complete binary search tree, print its elements in increasing order.

For example, the level order representation of the complete BST below is [15, 10, 20, 8, 12, 18, 25]. The solution should print [8, 10, 12, 15, 18, 20, 25].


Complete binary search tree

In the array representation of the binary tree, the left child for a node at index i occupies the index 2i+1, and the right child occupies the index 2i+2. For a complete binary tree, there will be no vacant positions in the array.
The idea is to process the array similarly as an inorder traversal of the binary tree using the above property since our binary tree is a BST—the inorder traversal prints the elements in increasing order.
The algorithm can be implemented as follows in C, Java, and Python.

C

Download   Run Code

Output:

8 10 12 15 18 20 25

Java

Download   Run Code

Output:

8 10 12 15 18 20 25

Python

Download   Run Code

Output:

8 10 12 15 18 20 25

Download   Run Code
Output:

8 10 12 15 18 20 25

Download   Run Code
Output:

8 10 12 15 18 20 25

Download   Run Code
Output:

8 10 12 15 18 20 25

The time complexity of the above solution is O(n) and the auxiliary space used by the program is O(n) for call stack.

The algorithm can be easily implemented iteratively as well. Below is the iterative version in C++, Java, and Python using explicit stack:

C++

Download   Run Code

Output:

8 10 12 15 18 20 25

Java

Download   Run Code

Output:

8 10 12 15 18 20 25

Python

Download   Run Code

Output:

8 10 12 15 18 20 25

Download   Run Code
Output:

8 10 12 15 18 20 25

Download   Run Code
Output:

8 10 12 15 18 20 25

Download   Run Code
Output:

8 10 12 15 18 20 25

The time complexity of the above solution is O(n) and the auxiliary space used by the program is O(n) for stack data structure.

source