二叉树链表的结构声明:
struct tree
{
int data;
struct tree *left;
stryct tree *right;
};
typedef struct tree treenode;
typedef treenode *btree;
using namespace std;
struct tree //二叉树结构声明
{
int data;
struct tree *left;
struct tree *right;
};
typedef struct tree treenode;
typedef treenode *btree;
/*----插入二叉树的结点-------*/
btree insertnode(btree root,int value)
{
btree newnode; //树根指针
btree current; //目前树结点指针
btree back; //父结点指针
/*-----创建结点内存----*/
newnode=(btree)malloc(sizeof(treenode));
/*-------初始化-----*/
newnode->data=value;
newnode->left=NULL;
newnode->right=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 createbtree( int *data,int len)
{
btree root=NULL;
int i;
for(i=0;i<len;i++)
root=insertnode(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=createbtree(data,9);
printf("树的结点内容:\n");
printbtree(root);
}