话不多说,上代码,看结果。
#include <stdio.h>
#include <malloc.h>
typedef struct node1
{
char data;
struct node1 *lchild,*rchild;
}BTCHINALR;
BTCHINALR * createbt( )
{
BTCHINALR *q;
struct node1 *s[300];
int j,i,x;
printf("建立二叉树,输入结点对应的编号和值,编号和值之间用逗号隔开\n\n");
printf("i,x = ");
scanf("%d,%d",&i,&x);
while(i != 0 && x != '$')
{
q = (BTCHINALR*)malloc(sizeof(BTCHINALR)); /*建立一个新结点q*/
q->data = x;
q->lchild = NULL;
q->rchild = NULL;
s[i] = q; /*q新结点地址存入s指针数组中*/
if(i != 1) /*i = 1,对应的结点是根结点*/
{
j = i / 2; /*求双亲结点的编号j*/
if(i % 2 == 0)
s[j]->lchild = q; /*q结点编号为偶数则挂在双亲结点j的左边*/
else
s[j]->rchild = q;
} /*q结点编号为奇数则挂在双亲结点j的右边*/
printf("i,x = ");
scanf("%d,%d",&i,&x);}
return s[1]; /*返回根结点地址*/
}
void inorder(BTCHINALR *bt)/* 中序遍历二叉树(递归算法)*/
{
if(bt != NULL)
{
inorder(bt->lchild);
printf("%d ",bt->data);
inorder(bt->rchild);
}
}
void frontorder(BTCHINALR *bt)/*前序遍历二叉树(递归算法)*/
{
if(bt != NULL)
{
printf("%d ",bt->data);
frontorder(bt->lchild);
frontorder(bt->rchild);
}
}
void lateorder(BTCHINALR *bt)/*后序遍历二叉树(递归算法)*/
{
if(bt != NULL)
{
lateorder(bt->lchild);
lateorder(bt->rchild);
printf("%d ",bt->data);
}
}
int main( )
{
BTCHINALR *bt;
char ch;
bt = createbt();
printf("\n前序遍历二叉树: ");
frontorder(bt);
printf("\n");
printf("\n中序遍历二叉树: ");
inorder(bt);
printf("\n");
printf("\n后序遍历二叉树: ");
lateorder(bt);
}
结果如下图。
就先这样,遇到别的再补充。