Sep 29, 2012 at 8:44pm UTC
Can someone please see whats the matter.
The search function is not working.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
#include<iostream>
using namespace std;
const unsigned size = 6;
struct Tree
{
int Key;
string Data;
Tree* left;
Tree* right;
};
Tree* vert(int k)
{
Tree* S = new Tree;
S->Key = k;
S->left = NULL;
S->right = NULL;
return S;
}
Tree* Search (int k,Tree* X)
{
if (X == NULL) return NULL;
else if (X->Key<k) return Search(k,X->left);
else if (X->Key>k) return Search(k,X->right);
else if (X->Key == k) return X;
}
Tree* add(int k,Tree* X)
{
if (X == NULL)
{
X = vert(k);
}
else if (k < X->Key) X->left = add(k,X->left);
else if (k > X->Key) X->right = add(k,X->right);
return X;
}
void printTree(Tree* X)
{
if (X == NULL) return ;
cout<<X->Key<<" - HEAD!!" <<endl;
cout<<"Now the left part\n" ;
printTree(X->left);
cout<<"Now right \n" ;
printTree(X->right);
}
int main()
{
Tree* T = NULL;
Tree* res;
bool result;
int a,i=0;
string w;
for (i=0;i<size;i++)
{
cout<<"Cin vertex\n" ;
cin>>a;
T = add(a,T);
}
res = Search(5,T);
cout<<res->Key<<endl;
printTree(T);
}
Last edited on Sep 30, 2012 at 6:59am UTC
Sep 29, 2012 at 9:01pm UTC
Are you getting an error when your going to compile or is something not working? Post the problem/error.
Sep 30, 2012 at 7:10am UTC
It works only if I'm searching for the root
Sep 30, 2012 at 8:11am UTC
Oh lol sorry you did post the problem you said the search function wasnt working, so sorry i missed that, i havent really done anything like that, but my guess would be because of the return statements in the search function, i mean i could be wrong and if i am im sure someone else ill help you.
If it does happen to be the return statments though, try putting them at the end of the search function.