用C语言创建二叉树并先序遍历
用C语言创建二叉树并
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
char data;
struct node *lchild,*rchild;
}BT;
BT *CreateBT()
{
BT *q, *s[30];
int i,j;
char x;
printf("\n\n请输入二叉树的节点编号和节点数据(例:1,A)\n注意:结束输入时节点编号输入0,节点数据任意!\n\n");
printf("编号,数据:");
scanf("%d,%c",&i,&x);
while(i!=0)
{
q=(BT*)malloc(sizeof(BT));
q->data=x;
q->lchild=NULL;q->rchild=NULL;
s[i]=q;
if(i!=1)
{
j=i/2;
if(i%2==0)
s[j]->lchild=q;
else
s[j]->rchild=q;
}
printf("编号,数据:");
scanf("%d,%c",&i,&x);
}
return s[1];
}
void Preorder(BT* bt)/*先序遍历*/
{
if(bt!=NULL)
{
printf(" %c ",bt->data);
Preorder(bt->lchild);
Preorder(bt->rchild);
}
}
void Preorder2(BT* bt)/*先序遍历度为2的节点*/
{
if( bt != NULL )
{
if(bt->lchild !=NULL && bt->rchild !=NULL )
{ printf(" %c ",bt->data);
Preorder2(bt->lchild);
Preorder2(bt->rchild);
}
}
}
void Preorder1(BT* bt)/*先序遍历度为1的节点*/
{
if( bt != NULL )
{
if((bt->lchild ==NULL && bt->rchild !=NULL) || (bt->lchild !=NULL && bt->rchild ==NULL))
printf(" %c ",bt->data);
else
{ Preorder1(bt->lchild);
Preorder1(bt->rchild);
}
}
}
void Preorder0(BT* bt)/*先序遍历度为0的节点*/
{
if( bt != NULL )
{
if(bt->lchild ==NULL && bt->rchild ==NULL )
printf(" %c ",bt->data);
else
{ Preorder0(bt->lchild);
Preorder0(bt->rchild);
}
}
}
main()
{
BT *bt=CreateBT();
printf("\n\n先序遍历输出所有节点:");
Preorder(bt);
printf("\n");
printf("\n先序遍历输出所有度为2的节点:");
Preorder2(bt);
printf("\n");
printf("\n先序遍历输出所有度为1节点:");
Preorder1(bt);
printf("\n");
printf("\n先序遍历输出所有度为0节点:");
Preorder0(bt);
printf("\n\n");
system("pause");
}