您的位置:首页 > 其它

hdu 3999 The order of a Tree(二叉搜索树)

2013-09-05 15:21 465 查看
在做另一道题的时候需要用到二叉搜索树,不过我不了解这种数据结构,所以学习一下。

这道题的话就是建立一个二叉搜索树,然后先序输出。

数组建树:

#include<stdio.h>
#include<string.h>
#define N 100005
struct node
{
int x;
int lson,rson;
} a[N*2];
int cnt;
int InsertTree(int t,int x)
{
if(t==0)
{
t=cnt++;
a[t].lson=0;
a[t].rson=0;
a[t].x=x;
}
else
{
if(x>a[t].x)
a[t].rson=InsertTree(a[t].rson,x);
else
a[t].lson=InsertTree(a[t].lson,x);
}
return t;
}
void print(int t)
{
if(t!=0)
{
printf(" %d",a[t].x);
print(a[t].lson);
print(a[t].rson);
}
return ;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i,t;
scanf("%d",&t);
a[1].x=t;
a[1].lson=0;
a[1].rson=0;
cnt=2;
for(i=2; i<=n; i++)
{
scanf("%d",&t);
InsertTree(1,t);
}
printf("%d",a[1].x);
print(a[1].lson);
print(a[1].rson);
printf("\n");
}
return 0;
}


链表建树:

#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct node
{
int x;
node *lson,*rson;
}*root;
node *InsertTree(node *root,int x)
{
if(root==NULL)
{
root=(node *)malloc(sizeof(node));
root->lson=NULL;
root->rson=NULL;
root->x=x;
}
else
{
if(root->x>x) root->lson=InsertTree(root->lson,x);
else root->rson=InsertTree(root->rson,x);
}
return root;
}
void print(node *root)
{
if(root!=NULL)
{
printf(" %d",root->x);
print(root->lson);
print(root->rson);
}
return ;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i,x;
root=NULL;
for(i=1; i<=n; i++)
{
scanf("%d",&x);
root=InsertTree(root,x);
}
printf("%d",root->x);
print(root->lson);
print(root->rson);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: