1.数组建树给一个普通序列:567432
#include<stdio.h>
#include<string.h>
int tree1[300010];
int s[300010];
int n;
void Insert(int w,int *tree)
{
int c=w;
int now=1;
while(tree[now]!=-1)//没有被赋值
{
if(tree[now] < c)//当前数比数根大
now = now*2 + 1;//右孩子
else
now = now*2;//左孩子
}
tree[now] = c;
}
void build(int *s,int *tree)
{
tree[1] = s[0] ;
for(int i = 1 ; i < n ; i++)
Insert(s[i],tree);
}
int main()
{
scanf("%d",&n);
memset(tree1,-1,sizeof(tree1));
for(int i=0; i<n; i++)
scanf("%d",&s[i]);
build(s,tree1);
return 0;
}
2.使用链表建树,前序遍历输出
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
typedef struct node
{
int data;
node *lchild,*rchild;
}*Tree,tree;
Tree root;
int n;
void insert(Tree& root , int t)
{
if(root==NULL)//如果为空==没有被赋值
{
root = (Tree)malloc(sizeof(tree));//开辟一个新单元
root->data = t;
root->lchild = NULL;
root->rchild = NULL;
}
else if(t < root->data)//当前数比树根小是左孩子,否则是右孩子
{
insert(root->lchild , t);//左孩子
}
else insert(root->rchild , t);//右孩子
}
void preoder(Tree root,int& cnt)//先序遍历
{
if(root==NULL)
return ;
cnt++; //用于控制输出格式
if(cnt!=n)
printf("%d ",root->data);
else
printf("%d\n",root->data);
preoder(root->lchild,cnt);
preoder(root->rchild,cnt);
}
int main()
{
scanf("%d",&n);
int t;
for(int i=0; i<n; i++)
{
scanf("%d",&t);
insert(root,t);//建树
}
int cnt=0;
preoder(root,cnt);//先序遍历
return 0;
}
本文介绍两种构建二叉搜索树的方法:一种是使用数组,另一种是利用链表,并通过C语言实现。文章提供了完整的源代码,包括数组构建树的过程及链表构建树并进行前序遍历输出的示例。
1891

被折叠的 条评论
为什么被折叠?



