Knowing that the inorder traversal of BSTs produces sorted lists, write an iterative function function that given 2 BSTs, the function checks whether the elements of both BSTs are the same or not. The time complexity of your algorithm should be \(O(max(m, n))\), where \(m\) and \(n\) are the numbers of elements in the two BSTs .
Difficulty level
This exercise is mostly suitable for students
int samei(Btree A, Btree B)
{
stack s1 = CreateStack();
stack s2 = CreateStack();
int done1 = 0;
int done2 = 0;
int v1, v2;
while (!done1 && !done2){
while (!done1){
if (A){
Push(&s1, A);
A = A->left;
}
else{
if (Top(s1, &A)){
Pop(&s1);
v1 = A->data;
A = A->right;
break;
}
else
done1 = 1;
}
}
while (!done2){
if (B){
Push(&s2, B);
B = B->left;
}
else{
if (Top(s2, &B)){
Pop(&s2);
v2 = B->data;
B = B->right;
break;
}
else
done2 = 1;
}
}
if (done1 == 1 && done2 == 1) return 1;
if (v1 != v2) return 0;
done1 = 0;
done2 = 0;
}
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
UVA 10009 - All Roads Lead Where