ccyy's coding zone
往前走,不要留恋路边的风景.
posts - 25,comments - 9,trackbacks - 0
    今天纠结了一下二叉排序树的一些操作..插入,查找,前序,中序和后序遍历
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct bTree
{
int data;
int key;
struct bTree *L;
struct bTree *R;
};

bTree *insertnode(bTree *root,int key,int value)
{
bTree *newnode;
bTree *current;
bTree *back;
newnode=(bTree*)malloc (sizeof(bTree));
newnode->data=value;
newnode->L=NULL;
newnode->R=NULL;
newnode->key=key;

if (root==NULL)
{
//printf("\nIt is error!No element!\n");
return newnode;
}
else
{
current=root;
while(current!=NULL)
{
back=current;
if (current->key>value)
current=current->L;
else
current=current->R;
}
if (back->key>value)
back->L=newnode;
else
back->R=newnode;
}
return root;
 }

bTree *createbtree()
 {
bTree *root=NULL;
int data,key,n;
scanf("%d",&n);
while(n--)
{
scanf("%d %d",&key,&data);
root=insertnode(root,key,data);
}
return root;
 }

void PreOrder(bTree *p)
{
if(p)
{
printf("%d  ",p->key);
PreOrder(p->L);
PreOrder(p->R);
}
}
void InOrder(bTree *p)
{
if(p)
{
InOrder(p->L);
printf("%d  ",p->key);
InOrder(p->R);
}
}
void PostOrder(bTree *p)
{
if(p)
{
PostOrder(p->L);
PostOrder(p->R);
printf("%d  ",p->key);
}
}

bool search(bTree *p,int key,int &data)
{
if(p)
{
if(p->key==key)
{
data=p->data;
return true;
}
else if(key<p->key)
return search(p->L,key,data);
else
return search(p->R,key,data);
}
return false;

}
void depth(bTree *p,int lev,int *pe)
{
if(p)
{
if(lev>*pe)
{
*pe=lev;
}
depth(p->L,lev+1,pe);
depth(p->R,lev+1,pe);

}
}

int main()
{
bTree *p;
int n,i=1,j=0;
p=createbtree();
PreOrder(p);
printf("\n");
InOrder(p);
printf("\n");
PostOrder(p);
printf("\n");
depth(p,i,&j);
int key,data;
scanf("%d",&key);
if(search(p,key,data))
printf("%d\n",data);
printf("\n");
return 0;
}
posted on 2010-07-26 17:05 ccyy 阅读(159) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理