Given two integer arrays, X and Y, representing a set of BST keys, check if they represent the same BSTs or not without building the tree. Assume that the keys are inserted into the BST in the same order as they appear in the array.

For example, consider the following arrays:

X[] = { 15, 25, 20, 22, 30, 18, 10, 8, 9, 12, 6 }
Y[] = { 15, 10, 12, 8, 25, 30, 6, 20, 18, 9, 22 }

 
Both arrays represent the same BSTs, as shown below:

Binary Search Tree

Practice this problem

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Given keys represent the same BSTs

Java


Download  Run Code

Output:

Given keys represent the same BSTs

Python


Download  Run Code

Output:

Given keys represent the same BSTs

The time complexity of the above solution is O(n2), where n is the size of the BST. The auxiliary space required by the program is O(n2).