二叉树的数组实现


递归建立二叉树,中序遍历。。。。

View Code
#include <stdio.h>
#include
<string.h>
#include
<stdlib.h>
#define N 10000

int l[N], r[N], key[N], flag;

void insert(int index, int x)
{
if(x <= key[index])
{
if(l[index] == -1) l[index] = flag;
else insert(l[index], x);
}
else
{
if(r[index] == -1) r[index] = flag;
else insert(r[index], x);
}
}

void preorder(int index)
{
if(l[index] != -1) preorder(l[index]);
printf(
"%d ",key[index]);
if(r[index] != -1) preorder(r[index]);
}

int main()
{
int x, root, n;
memset(l,
-1, sizeof(l));
memset(r,
-1, sizeof(r));
scanf(
"%d",&n);
root
= -1; flag = 0;
while(n--)
{
scanf(
"%d", &x);
if(root == -1) key[++root] = x;
else
{
key[
++flag] = x;
insert(root, x);
}
}
preorder(root);
return 0;
}
posted @ 2011-07-24 10:03  AC_Von  阅读(291)  评论(0编辑  收藏  举报