#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild, *rchild;
}node, *btree;
btree createNode(int num)
{
btree newnode = (btree)malloc(sizeof(node));
newnode->data = num;
return newnode;
}
void CreateBtreeFromArray(btree *root, int array[], int begin, int end)
{
if((end - begin) == 1)
{
*root = createNode(array[0]);
(*root)->lchild = NULL;
(*root)->rchild = NULL;
}
else
{
int mid = begin + (end - begin) / 2;
*root = createNode(array[1]);
CreateBtreeFromArray(&(*root)->lchild, array, begin, mid);
//CreateBtreeFromArray(&(*root)->rchild, array, mid + 1, end);
CreateBtreeFromArray(&(*root)->rchild, array, mid, end);
}
}
void in(btree root)
{
if(root)
{
in(root->lchild);
printf("[%d ] ", root->data);
in(root->rchild);
}
}
int main(void)
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = sizeof(a) / sizeof(int);
btree root;
CreateBtreeFromArray(&root, a, 0, len);
in(root);
putchar('\n');
return 0;
}
|