#include <stdio.h>
#include <stdlib.h>
//结构体的封装
typedef struct TreeNode{
char data;
struct TreeNode *leftchild,*rightchild;
}TreeNode;
//先序建立二叉树
void CreateTree(TreeNode *&T){
char x;
scanf("%c",&x);
if(x=='#') T=NULL;
else{
T=(TreeNode *)malloc(sizeof(TreeNode));
T->data=x;
CreateTree(T->leftchild);
CreateTree(T->rightchild);
}
}
二叉树的遍历
//先序遍历二叉树
void FiPrintfTree(TreeNode *T){
if(T!=NULL){
printf("%c",T->data);
FiPrintfTree(T->leftchild);
FiPrintfTree(T->rightchild);
}
}
//中序遍历二叉树
void SePrintfTree(TreeNode *T){
if(T!=NULL){
SePrintfTree(T->leftchild);
printf("%c",T->data);
SePrintfTree(T->rightchild);
}
}
//后序遍历二叉树
void ThPrintfTree(TreeNode *T){
if(T!=NULL){
ThPrintfTree(T->leftchild);
ThPrintfTree(T->rightchild);
printf("%c",T->data);
}
}
主函数封装
int main()
{
TreeNode *P;
printf("请先序输入二叉树,空用‘#’代替:\n");
CreateTree(P);
printf("先序遍历为:\n");
FiPrintfTree(P),
printf("\n中序遍历为:\n");
SePrintfTree(P);
printf("\n后序遍历为:\n");
ThPrintfTree(P);
return 0;
}
二叉树的遍历序列与建立二叉树所输入的序列不同,以二叉树(a)为例,结点B无直接后继,故左右孩子应输入为空,用‘#’代替。
运行结果如下图所示
(a)
(b)