编写一个程序,实现二叉树的各种基本运算,并在此基础上设计一个主程序完成如下功能:

2024-11-08 03:47:19
推荐回答(1个)
回答(1):

#include
#include
typedef struct node* link;
struct node{
char item;
link l,r;
int counter;
};
link makenode(char key)
{
link p = (link)malloc(sizeof(struct node));
p->item = key; p->counter = 0;
p->l=p->r=NULL;
return p;
}
link insert(link p,char key)
{
if(!p){
link tmp = makenode(key);
tmp->counter++;
return tmp;
}
if( key < p->item)
p->l = insert(p->l,key);
if(key > p->item)
p->r = insert(p->r,key);
if(key == p->item)
p->counter++;
return p;
}
void travel(link p,int layer)
{
if(!p)
return ;
travel(p->l,layer+1);
printf("node :%c(c\t%d)(l\t%d)\n",p->item,p->counter,layer);
travel(p->r,layer+1);
}
int count(link t)
{
if(!t)
return 0;
return 1 + count(t->l) +count(t->r);
}
int depth(link t)
{
int dl,dr;
if(!t)
return 0;
dl = depth(t->l);
dr = depth(t->r);
return 1+(dl>dr?dl:dr);
}
link search(link p,char key)
{
if(!p)
return NULL;
if(key < p->item)
return search(p->l,key);
if(key > p->item)
return search(p->r,key);
return p;
}
int main(void )
{
link p;
link root = NULL;
root = makenode('1');
root->l = makenode('2');
root->r = makenode('3');
root->l->l = makenode('4');
root->l->r = makenode('5');
root->r->r = makenode('6');
travel(root,0);
printf("\n");
printf("count is %d\n",count(root));
printf("depth is %d\n",depth(root));
p = search (root,'1');
if(p)
printf("find node :%c c = %d\n",p->item,p->counter);
return 0;
}