我想出了一种算法来检查两棵树是否在结构上相似,即两棵树中相应节点的数据可能不同,但如果tree1中的一个节点有一个左子,那么它的相应节点就在tree2也必须有一个左孩子。
算法(node * root1,node * root2):
1. Create 2 queues Q1,Q2 and enqueue root1 and root2.
2. while(Q1 and Q2 are not empty)
2.a temp1 = deQ(Q1);
2.b temp2 = deQ(Q2);
2.c if temp1 has left child then enqueue temp1's left child in Q1
2.d if temp2 has left child then enqueue temp2's left child in Q2
2.e if temp1 has right child then enqueue temp1's right child in Q1
2.f if temp2 has right child then enqueue temp2's right child in Q2
2.g now check if the size of Q1 and Q2 is equal
2.h if the size is equal then continue else the two trees are not similar
3. End
这个算法是否正确?
答案 0 :(得分:1)
目前你的算法不起作用。例如,如果tree1
root只有一个正确的子项而tree2
只有一个左子项,那么您的算法将输出一个误报。
您必须按如下方式修改算法。这是一种递归方法,但还有其他方法。
Algorithm(node * root1, node * root2) :
// if exactly one is NULL and other is not, return false.
if ( root1 && !root2 ) || ( !root1 && root2 )
return 0.
// if both are NULL, return true.
if ( !root1 && !root2 )
return 1.
// Both are valid nodes. So now check there respective child sub-trees.
return Algorithm( root1->left, root2->left ) && Algorithm( root1->right, root2->right )
您的算法:
Algorithm(node * root1, node * root2) :
1. Create 2 queues Q1,Q2 and enqueue root1 and root2.
// here you skip the Null check for root1 and root2. Should be added.
2. while(Q1 is not empty or Q2 is not empty)
2.a temp1 = deQ(Q1);
2.b temp2 = deQ(Q2);
// Now Compare the respective children of temp1 & temp2. If not equal, then return false.
2.c if temp1 has left child then enqueue temp1's left child in Q1
2.d if temp2 has left child then enqueue temp2's left child in Q2
2.e if temp1 has right child then enqueue temp1's right child in Q1
2.f if temp2 has right child then enqueue temp2's right child in Q2
3. return true.