Given a distinct sequence of keys, check if it represents a preorder traversal of a binary search tree (BST).

For example, the following BST can be constructed from the sequence {15, 10, 8, 12, 20, 16, 25} and it has the same preorder traversal:

BST

Practice this problem

The idea is first to construct a BST from the given sequence by inserting keys into the BST one at a time and then compare the preorder traversal of the constructed BST with the given sequence. If the order matches, we can say that the given sequence represents the preorder traversal of a BST.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

Given sequence represents preorder traversal of a BST

Java


Download  Run Code

Output:

Given sequence represents preorder traversal of a BST

Python


Download  Run Code

Output:

Given sequence represents preorder traversal of a BST

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

 
We can reduce the time complexity to O(n) by constructing a BST from the given sequence in a preorder fashion. Now the problem reduces to just validating if the whole sequence is traversed or not while constructing the BST. If the whole sequence is traversed, we can say that the given sequence represents the preorder traversal of a BST.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

Given sequence represents preorder traversal of a BST

Java


Download  Run Code

Output:

Given sequence represents preorder traversal of a BST

Python


Download  Run Code

Output:

Given sequence represents preorder traversal of a BST

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.