I'm trying write a function to check if two trees have the same structure, regardless of values, and the code that I wrote so far doesn't work. Any help or pointers (pun intended) would be greatly appreciated.
template <class T>
bool BST<T>::similarStructure(BST Tree2) {
if (isEmpty()) {
cout << "tree is empty\n";
return;
}
StackArray<node<T>> s1, s2; // s1 for traversal,, s2 for printing
s1.Push(root);
s2.Push(tree2.root);
while (!s1.IsEmpty() &&!s2.isempty()) {
node<T> n = s1.Pop();
node<T> n1=s2.Pop();
if (n->right != NULL && n1->right!=NULL){
s1.Push(n->right);
s2.Push(n1->right); }
else{
return false;}
if (n->left != NULL && n->left!=NULL){
s1.Push(n->left);
s2.Push(n1->left);}
else{
return false;}
}
return true;
I must be in a generous mood.
A simple in-order traversal will solve the problem. Just check at each node that the left field is null or not null in both trees, same test for the right field, then recurse.
This template function does the work, you need to call it with the root node pointer of your two trees.
Untested code.