/*
1.构建如下二叉树:
A
/ \
B C
/ \ /
D E F
2.分别使用先序、中序、遍历输出二叉树的结点
*/
/* 二叉树的结点结构 */
#include <stdio.h>
#include <malloc.h>
typedef char ElemType; /* 数据域值类型 */
typedef struct Node {
ElemType data; /* 数据域 */
struct Node *lchild, *rchild; /* 左、右指针域,分别存储左、右孩子的存储位置 */
} BinaryTree;
/* 先序建立二叉树 */
BinaryTree *CreBiTree( ) {
BinaryTree *bt;
ElemType x;
scanf("%c", &x);
if (x == '#') {
bt = NULL;
} else {
bt = (BinaryTree *)malloc(sizeof(BinaryTree));
bt->data = x;
bt->lchild = CreBiTree();
bt->rchild = CreBiTree();
}
return bt;
}
/* 先序遍历二叉树的递归算法 */
void PreOrder(BinaryTree *bt) {
if (bt != NULL) {
printf("%c", bt->data);
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
/* 中序遍历二叉树的递归算法 */
void InOrder(BinaryTree *bt) {
if (bt != NULL) {
InOrder(bt->lchild);
printf("%c", bt->data);
InOrder(bt->rchild);
}
}
/* 后序遍历二叉树的递归算法 */
void PostOrder(BinaryTree *bt) {
if (bt != NULL) {
PostOrder(bt->lchild);
PostOrder(bt->rchild);
printf("%c", bt->data);
}
}
void main() {
BinaryTree *bt;
printf("input data:");
bt = CreBiTree();
printf("PreOrder result:");
PreOrder(bt);
printf("\n");
printf("InOrder result:");
InOrder(bt);
printf("\n");
printf("PostOrder result:");
PostOrder(bt);
printf("\n");
}