I'm trying to solve a problem, where we can find,if we are given two trees, if second is subtree of first.
Here is basic implementation my BST. Implemented in one go, without any error
Now, I'm trying to write another function, which can solve the problem I have stated above:
//Checks if second tree is subtree of first.
//Friend of class "BST". To use pHead
bool compareSub(Node *p,Node *q);//Helper for CheckSubTree operator overloaded function
bool CheckSubTree(BST t1, BST t2)
{
static bool flag = 0; //Assume that t2 is not subtree of t1
//When both tree are empty
if(t1.pHead == NULL && t2.pHead == NULL)
{
flag = 0;
return flag;
}
//When only t2 is empty
if(t2.pHead == NULL)
{
flag = 0;
return flag;
}
Node *temp1, *temp2;
temp1 = t1.pHead;
temp2 = t2.pHead;
while(temp1 != NULL)
{
if(temp1->data == temp2->data) //If data at nodes are same then
{ //compare the rest of data
flag = compareSub(temp1,temp2);
return flag;
}
if(temp1->data > temp2->data)
{
temp1 = temp1->left;
}
else
{
temp1 = temp1->right;
}
}
//If flag was not set by above while loop, implies, t2 is not subtree of t1
return flag;
}
bool compareSub(Node *p,Node *q)//Helper for CheckSubTree operator overloaded function
{
static bool flag1 = 1;
if(p == NULL && q == NULL)
return flag1;
if(p->data == q->data && flag1 == 1)
{
flag1 = compareSub(p->left,q->left);
flag1 = compareSub(p->right,q->right);
}
else flag1 = 0;
return flag1;
}
I have attached updated BinaryTree.hpp header file below. (includes "friend bool CheckSubTree(BST t1, BST t2);" in BST class). I have also attached the other two files, main.txt and SubTree.txt, just in case you wanna give it a local run.
Its giving segmentation fault, when the execution goes to compareSub(Node *p,Node *q. I've implemented whole thing on my own, so this may not be the most efficient way to do it. Can anybody point out my mistake. I'm also trying to debug it.
Here is the stack trace:
#0 77A415DE ntdll!LdrQueryProcessModuleInformation() (C:\windows\system32\ntdll.dll:??) #1 77A415DE ntdll!LdrQueryProcessModuleInformation() (C:\windows\system32\ntdll.dll:??) #2 77A3014E ntdll!LdrFindResource_U() (C:\windows\system32\ntdll.dll:??) #3 00000000 0x0028f8cc in ??() (??:??) #4 00000000 0x0028f91c in ??() (??:??) #5 00000000 0x00000000 in ??() (??:??)
Attached File(s)
-
BinaryTree.txt (7.21K)
Number of downloads: 31 -
main.txt (3.46K)
Number of downloads: 25 -
SubTree.txt (1.46K)
Number of downloads: 32

New Topic/Question
Reply



MultiQuote




|