如果自上而下按层次,自左至右输入每一个结点的一个三元组(N,P, L/R)。当中N 为本结点的元素。P为其父结点。L 指示N为P 的左孩子,R指示N 为P的右孩子。试写一个建立二元树的左右链表示算法,并实现先根、中根、后根以及层序遍历算法。
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef int Elementtype;
struct node
{
struct node *lchild;
struct node *rchild;
Elementtype data;
};
typedef node *BTREE;
BTREE CreateTree();
int IsEmpty(BTREE root);
void Visit(int n);
void InOrder(BTREE root);
void PostOrder(BTREE root);
void PreOrder(BTREE root);
int main()
{
struct node *root;
BTREE tree[MAX];
root = CreateTree();
printf("中根遍历:\n");
InOrder(root);
printf("\n");
printf("先根遍历:\n");
PreOrder(root);
printf("\n");
printf("后根遍历:\n");
PostOrder(root);
printf("\n");
return 0;
}
BTREE CreateTree()
{
BTREE root;
BTREE newNode;
BTREE tree[MAX];
Elementtype data;
int number;//记录节点位置
int i;
int j=1;
char LR;
root = new struct node;//新建根节点
root->lchild = NULL;
root->rchild = NULL;
printf("输入根节点数据:\n");
scanf("%d",&data);
root->data = data;
number = 0;
tree[0] = root;
printf("输入三元组(节点数据。节点标号(从0開始),L/R),以输入0,0,0作为结束\n");
scanf("%d,%d,%c",&data,&i,&LR);
while(data!=0 || i!=0 || LR != '0')//以输入0,0,0作为结束
{
newNode = new struct node;
newNode->data = data;
number++;
tree[number] = newNode;
if(LR == 'L')
{
tree[i]->lchild = newNode;
}
if(LR == 'R')
{
tree[i]->rchild = newNode;
}
newNode->lchild = newNode->rchild = NULL;//初始化
printf("输入三元组(节点数据。节点标号。L/R),以输入0,0,0作为结束\n");
scanf("%d,%d,%c",&data,&i,&LR);
}
root = tree[0];
printf("层序遍历:\n");
for(i=0;i<number+1;i++)
printf("%d ",tree[i]->data);
printf("\n");
return root;
}
int IsEmpty(BTREE root)
{
if (root == NULL)
{
return 1;
}
else
return 0;
}
void Visit(Elementtype data)
{
printf("%d ",data);
}
void InOrder(BTREE root)//中根遍历
{
if (IsEmpty(root) == 0)
{
InOrder(root->lchild);
Visit(root->data);
InOrder(root->rchild);
}
}
void PreOrder(BTREE root)//先根遍历
{
if(IsEmpty(root) == 0)
{
Visit(root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void PostOrder(BTREE root)//后根遍历
{
if(IsEmpty(root) == 0)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
Visit(root->data);
}
}
以上供君參考