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

Practice this problem

1. Recursive Solution

In the array representation of the binary tree, the left child for a node at index i occupies index 2i+1, and the right child occupies 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

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.

2. Iterative Solution

The algorithm can be easily implemented iteratively as well. Following is the iterative version in C++, Java, and Python using an 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

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the BST.