【问题描述】先序遍历的顺序建立二叉树,输出中序遍历序列(按先序次序输入二叉树中结点的值,#号为空结点)
【输入形式】1 2 4 # # 5 # # 3 # 6 7 # # #
【输出形式】4251376
【注】C语言版
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct BiNode {
char data;
struct BiNode *lchild, *rchild;
} BiTNode, *BiTree;
void CreateBiTree(BiTree *T) {
char ch;
scanf(" %c", &ch); // 注意前面的空格,用于跳过空白字符
if (ch == '#') {
*T = NULL;
} else {
*T = (BiTree)malloc(sizeof(BiTNode));
(*T)->data = ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
void InOrderTraverse(BiTree T) {
if (T != NULL) {
InOrderTraverse(T->lchild);
printf("%c", T->data);
InOrderTraverse(T->rchild);
}
}
int main() {
BiTree tree;
printf("请输入二叉树的先序序列(空节点用#表示): ");
CreateBiTree(&tree);
printf("中序遍历结果: ");
InOrderTraverse(tree);
printf("\n");
return 0;
}
运行结果如下: