Apr 13, 2013 at 9:54pm UTC
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 69 70 71 72 73 74 75 76 77
#include <iostream>
using namespace std;
typedef struct node{
node*right;
node*left;
node*father;
int height;
int key;
}node,*pnode;
void insert(pnode p1,int n)
{ int h=1;
//init
pnode p;
p=new node;
p->key=n;
p->father=NULL;
p->right=NULL;
p->left=NULL;
if (p1==NULL)
{p1=p;
return ;
}//logic
if (p1->left==NULL&&n<p1->key)
{ p1->left=p;
p->father=p1;
return ;
}
if (p1->right==NULL&&n>p1->key)
{ p1->right=p;
p->father=p1;
return ;
}
if (n<p1->key)//recursive
{insert(p1->left,n);}
else if (n>p1->key)//recursive
{insert(p1->right,n);}
else
h++;
p->height=h;
return ;
}
pnode find(node*p,int k)
{
if (!p)
return NULL;
if (k<p->key)
return find(p->left,k);
else if (k>p->key)
return find(p->right,k);
else
return p;
}
int main()
{
pnode p=NULL;
insert(p,1);
insert(p,4);
insert(p,3);
pnode p2=find(p,4);
cout<<p2->key;
system("pause" );
return 0;
}
It exit with warning
Last edited on Apr 13, 2013 at 11:19pm UTC
Apr 13, 2013 at 11:04pm UTC
_ Your indentation is awful
_ Your code does not compile (extra } in line 77)
_ Making it compile, it would segfault, as you're trying to dereference a NULL pointer in line 71.
_ `insert()' is simply leaking memory. It does not modify `p'
Apr 14, 2013 at 12:15am UTC
I change line 17p=new node;
to p=(pnode)malloc(sizeof(node)); but it still doesn't work .
Apr 14, 2013 at 1:07am UTC
What I mean is that line 23 p1=p;
is useless.
You passed the argument by value, so `p' in main remains the same (NULL).