Check for Identical BSTs without building the trees
Last Updated : 23 Jul, 2025
Given two arrays that represent a sequence of keys. Imagine we make a Binary Search Tree (BST) from each array. The task is to find whether two BSTs will be identical or not without actually constructing the tree.
Examples:
Input: arr1[] = {2, 4, 1, 3} , arr2[] = {2, 4, 3, 1} Output: True Explanation: As we can see the input arrays are {2, 4, 3, 1} and {2, 1, 4, 3} will construct the same tree
Input: arr1[] = {8, 3, 6, 1, 4, 7, 10, 14, 13}, arr2[] = {8, 10, 14, 3, 6, 4, 1, 7, 13} Output: True Explanation: They both construct the same following BST.
Approach:
According to BST property, elements of the left subtree must be smaller and elements of right subtree must be greater than root. Two arrays represent the same BST if, for every element x, the elements in left and right subtrees of x appear after it in both arrays. And same is true for roots of left and right subtrees. The idea is to check of , if next smaller and greater elements are same in both arrays. Same properties are recursively checked for left and right subtrees.
Follow the steps below to solve the problem:
In both arrays by comparing values within a range defined by min and max constraints. This starts from the root node.
For both arrays, find the next element that satisfies the current range of values (greater than min and less than max) to identify valid children.
If no valid children are found in both arrays, return true as both subtrees are leaves.
If one array has a valid child and the other does not, or if the children found are not equal, return false.
Move to the next valid child and recursively check both left and right subtrees by updating min and max values based on the current child.
Combine the results of the recursive calls for both left and right subtrees, returning true only if both match at every step.
Below is the implementation of the above approach:
C++
// C++ program to check for Identical// BSTs without building the trees#include<bits/stdc++.h>usingnamespacestd;// Function to check if two arrays construct the same BSTboolisSameBSTUtil(vector<int>&arr1,vector<int>&arr2,intn,intl,intr,intlow,inthigh){intleftIdx,rightIdx;// Search for a valid element in arr1 and arr2// that satisfies the constraints `low` and `high`for(leftIdx=l;leftIdx<n;leftIdx++){if(arr1[leftIdx]>low&&arr1[leftIdx]<high){break;}}for(rightIdx=r;rightIdx<n;rightIdx++){if(arr2[rightIdx]>low&&arr2[rightIdx]<high){break;}}// If both arrays have no valid elements, return trueif(leftIdx==n&&rightIdx==n){returntrue;}// If one array has a valid element but the other doesn't,// or if the elements are different, return falseif(((leftIdx==n)^(rightIdx==n))||arr1[leftIdx]!=arr2[rightIdx]){returnfalse;}// Recursively check for the right and left subtreesreturnisSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,arr1[leftIdx],high)&&isSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,low,arr1[leftIdx]);}boolisSameBST(vector<int>&arr1,vector<int>&arr2,intn){returnisSameBSTUtil(arr1,arr2,n,0,0,INT_MIN,INT_MAX);}intmain(){// Hardcoded inputs for both the arraysvector<int>arr1={8,3,6,1,4,7,10,14,13};vector<int>arr2={8,10,14,3,6,4,1,7,13};intn=arr1.size();if(isSameBST(arr1,arr2,n)){cout<<"True";}else{cout<<"False";}return0;}
C
// C program to check for Identical// BSTs without building the trees#include<stdio.h>#include<limits.h>#include<stdbool.h>// Function to check if two arrays construct the same BSTboolisSameBSTUtil(intarr1[],intarr2[],intn,intl,intr,intlow,inthigh){intleftIdx,rightIdx;// Find the next element in bounds in arr1[]for(leftIdx=l;leftIdx<n;leftIdx++){if(arr1[leftIdx]>low&&arr1[leftIdx]<high)break;}// Find the next element in bounds in arr2[]for(rightIdx=r;rightIdx<n;rightIdx++){if(arr2[rightIdx]>low&&arr2[rightIdx]<high)break;}// If no valid elements in both arraysif(leftIdx==n&&rightIdx==n)returntrue;// Mismatch in structure or valuesif(((leftIdx==n)^(rightIdx==n))||arr1[leftIdx]!=arr2[rightIdx])returnfalse;// Recur for left and right subtreesreturnisSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,arr1[leftIdx],high)&&isSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,low,arr1[leftIdx]);}boolisSameBST(intarr1[],intarr2[],intn){returnisSameBSTUtil(arr1,arr2,n,0,0,INT_MIN,INT_MAX);}intmain(){// Hardcoded inputs for both the arraysintarr1[]={8,3,6,1,4,7,10,14,13};intarr2[]={8,10,14,3,6,4,1,7,13};intn=sizeof(arr1)/sizeof(arr1[0]);printf("%s\n",isSameBST(arr1,arr2,n)?"True":"False");return0;}
Java
// Java program to check for Identical// BSTs without building the treesimportjava.util.ArrayList;classGfG{// Function to check if two arrays construct the same BSTstaticbooleanisSameBSTUtil(ArrayList<Integer>arr1,ArrayList<Integer>arr2,intn,intl,intr,intlow,inthigh){intleftIdx,rightIdx;// Find the next element within bounds // in arr1[] and arr2[]for(leftIdx=l;leftIdx<n;leftIdx++){if(arr1.get(leftIdx)>low&&arr1.get(leftIdx)<high)break;}for(rightIdx=r;rightIdx<n;rightIdx++){if(arr2.get(rightIdx)>low&&arr2.get(rightIdx)<high)break;}// If no valid element is found in // both ArrayListsif(leftIdx==n&&rightIdx==n)returntrue;// Mismatch in structure or valuesif(((leftIdx==n)^(rightIdx==n))||!arr1.get(leftIdx).equals(arr2.get(rightIdx)))returnfalse;// Recur for left and right subtreesreturnisSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,arr1.get(leftIdx),high)&&isSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,low,arr1.get(leftIdx));}// Wrapper over isSameBSTUtil()staticbooleanisSameBST(ArrayList<Integer>arr1,ArrayList<Integer>arr2,intn){returnisSameBSTUtil(arr1,arr2,n,0,0,Integer.MIN_VALUE,Integer.MAX_VALUE);}publicstaticvoidmain(String[]args){ArrayList<Integer>arr1=newArrayList<>();ArrayList<Integer>arr2=newArrayList<>();// Directly assigning elements to ArrayListsarr1.add(8);arr1.add(3);arr1.add(6);arr1.add(1);arr1.add(4);arr1.add(7);arr1.add(10);arr1.add(14);arr1.add(13);arr2.add(8);arr2.add(10);arr2.add(14);arr2.add(3);arr2.add(6);arr2.add(4);arr2.add(1);arr2.add(7);arr2.add(13);intn=arr1.size();System.out.println(isSameBST(arr1,arr2,n)?"True":"False");}}
Python
# A Python program to check for Identical# BSTs without building the trees# Function to check if two arrays construct the same BSTdefisSameBSTUtil(arr1,arr2,n,l,r,low,high):# Find the next element within bounds in arr1[] and arr2[]whilel<n:iflow<arr1[l]<high:breakl+=1whiler<n:iflow<arr2[r]<high:breakr+=1# If no valid element is found in both arraysifl==nandr==n:returnTrue# Mismatch in structure or valuesif(l==n)^(r==n)orarr1[l]!=arr2[r]:returnFalse# Recur for left and right subtreesreturn(isSameBSTUtil(arr1,arr2,n,l+1,r+1,arr1[l],high)andisSameBSTUtil(arr1,arr2,n,l+1,r+1,low,arr1[l]))# A wrapper over isSameBSTUtil()defisSameBST(arr1,arr2,n):returnisSameBSTUtil(arr1,arr2,n,0,0,float('-inf'),float('inf'))if__name__=='__main__':# Hardcoded inputs for both the arraysarr1=[8,3,6,1,4,7,10,14,13]arr2=[8,10,14,3,6,4,1,7,13]n=len(arr1)print("True"ifisSameBST(arr1,arr2,n)else"False")
C#
// C# program to check for Identical // BSTs without building the trees usingSystem;usingSystem.Collections.Generic;classGfG{// Function to check if two arrays construct the same BSTstaticboolisSameBSTUtil(List<int>arr1,List<int>arr2,intn,intl,intr,intlow,inthigh){intleftIdx,rightIdx;// Search for a valid element in arr1 and arr2// that satisfies the constraints `low` and `high`for(leftIdx=l;leftIdx<n;leftIdx++)if(arr1[leftIdx]>low&&arr1[leftIdx]<high)break;for(rightIdx=r;rightIdx<n;rightIdx++)if(arr2[rightIdx]>low&&arr2[rightIdx]<high)break;// If both arrays have no valid elements, return trueif(leftIdx==n&&rightIdx==n)returntrue;// If one array has a valid element but // the other doesn't, or if the// elements are different, return falseif(((leftIdx==n)^(rightIdx==n))||arr1[leftIdx]!=arr2[rightIdx])returnfalse;// Make the current child as parent and // recursively check for left and right // subtrees of it.returnisSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,arr1[leftIdx],high)&&isSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,low,arr1[leftIdx]);}// A wrapper over isSameBSTUtil() staticboolisSameBST(List<int>arr1,List<int>arr2,intn){returnisSameBSTUtil(arr1,arr2,n,0,0,int.MinValue,int.MaxValue);}staticvoidMain(string[]args){// Hardcoded Inputs for the ArraysList<int>arr1=newList<int>{8,3,6,1,4,7,10,14,13};List<int>arr2=newList<int>{8,10,14,3,6,4,1,7,13};intn=arr1.Count;Console.WriteLine(isSameBST(arr1,arr2,n)?"True":"False");}}
JavaScript
// Javascript program to check for Identical// BSTs without building the trees// Function to check if two arrays construct the same BSTfunctionisSameBSTUtil(arr1,arr2,n,l,r,low,high){letleftIdx,rightIdx;// Find valid elements in arr1 and arr2 within boundsfor(leftIdx=l;leftIdx<n;leftIdx++){if(arr1[leftIdx]>low&&arr1[leftIdx]<high)break;}for(rightIdx=r;rightIdx<n;rightIdx++){if(arr2[rightIdx]>low&&arr2[rightIdx]<high)break;}// Both arrays have reached the endif(leftIdx==n&&rightIdx==n)returntrue;// Mismatch in structure or valuesif(((leftIdx==n)^(rightIdx==n))||arr1[leftIdx]!=arr2[rightIdx])returnfalse;// Recursively check left and right subtreesreturnisSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,arr1[leftIdx],high)&&isSameBSTUtil(arr1,arr2,n,leftIdx+1,rightIdx+1,low,arr1[leftIdx]);}// Wrapper functionfunctionisSameBST(arr1,arr2,n){returnisSameBSTUtil(arr1,arr2,n,0,0,Number.MIN_VALUE,Number.MAX_VALUE);}// Harcoded inputs for both arraysletarr1=[8,3,6,1,4,7,10,14,13];letarr2=[8,10,14,3,6,4,1,7,13];letn=arr1.length;console.log(isSameBST(arr1,arr2,n)?"True":"False");
Output
True
Time Complexity: O(n^2), because for each node, we recursively search through the rest of the arrays to find the corresponding nodes in both arrays. Auxiliary Space: O(h), where h is the height of tree.