本文是接上一篇文章写得。
这个结构体存放了树根的数据,以及指向左子树和右子树的指针。
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
主要用三个函数
btree insert_node( btree root ,int value)
btree creatbtree( int *data,int len )
void printbtree(btree root)
完成实现。
接下来是实现的过程
#include<stdio.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
typedef struct tree treenode;
typedef treenode *btree;
btree insert_node( btree root ,int value)
{
btree newnode;
btree current;
btree back;
newnode = (btree ) malloc(sizeof(treenode));
newnode->data = value;
newnode->left = NULL;
newnode->left = NULL;
if( root == NULL )
{
return newnode;
}
else
{
current = root;
while(current != NULL )
{
back = current;
if( current->data > value )
current = current->left;
else
current = current->right;
}
if(back->data > value)
back->left =newnode;
else
back->right =newnode;
}
return root;
}
btree creatbtree( int *data,int len )
{
btree root = NULL;
int i;
for( i = 0; i < len ; i++)
{
root = insert_node( root , data[i] );
}
return root;
}
void printbtree(btree root)
{
btree ptr;
ptr = root->left;
printf("输出左子树\n");
while( ptr != NULL )
{
printf("[%2d]\n",ptr->data);
ptr = ptr->left;
}
ptr = root->right;
printf("输出右子树\n");
while( ptr != NULL )
{
printf("[%2d]\n",ptr->data);
ptr = ptr->right;
}
}
int main()
{
btree root = NULL;
int data[10] ={5,6,4,8,2,3,7,1,9};
root = creatbtree(data,9);
printf("树的结点内容\n");
printbtree(root);
return 0 ;
}