# include <stdio.h>
# include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode{
ElemType data;//节点数据
struct BiTNode* Lchild;//左孩子指针
struct BiTNode* Rchild;//有孩子指针
}BiTNode,*BiTree;
//构造二叉树
void createbt(BiTree &T){
char ch;
scanf("%c",&ch);
if(ch=='#')T=NULL;
else{
T=(BiTree)malloc(sizeof(BiTNode));
T->data=ch;
createbt(T->Lchild);
createbt(T->Rchild);
}
}
//先序遍历(根 左 右)
void Preorder(BiTree T){//先序遍历以T为根节点的二叉树
if(T){//二叉树为空不做任何操作
printf("%c",T->data);//通过函数指针*visit访问根节点
Preorder(T->Lchild);
Preorder(T->Rchild);
}
}
//中序遍历(左 根 右)
void Inorder(BiTree T){
if(T){
Inorder(T->Lchild);
printf("%c",T->data);
Inorder(T->Rchild);
}
}
//后序遍历(左 右 根)
void Postorder(BiTree T){
if(T){
Postorder(T->Lchild);
Postorder(T->Rchild);
printf("%c",T->data);
}
}
/*
A
/ \
B #
/ \
C D
/ \ / \
# # E F
/ \ / \
# G # #
/ \
# #
以先序遍历的形式输入:ABC##DE#G##F###
*/
void main(){
BiTree T;
printf("create a tree such as abc##de#g##f###\n");
createbt(T);
printf("\n/*先序遍历*/");
Preorder(T);
printf("\n/*中序遍历*/");
Inorder(T);
printf("\n/*后序遍历*/");
Postorder(T);
}
# include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode{
ElemType data;//节点数据
struct BiTNode* Lchild;//左孩子指针
struct BiTNode* Rchild;//有孩子指针
}BiTNode,*BiTree;
//构造二叉树
void createbt(BiTree &T){
char ch;
scanf("%c",&ch);
if(ch=='#')T=NULL;
else{
T=(BiTree)malloc(sizeof(BiTNode));
T->data=ch;
createbt(T->Lchild);
createbt(T->Rchild);
}
}
//先序遍历(根 左 右)
void Preorder(BiTree T){//先序遍历以T为根节点的二叉树
if(T){//二叉树为空不做任何操作
printf("%c",T->data);//通过函数指针*visit访问根节点
Preorder(T->Lchild);
Preorder(T->Rchild);
}
}
//中序遍历(左 根 右)
void Inorder(BiTree T){
if(T){
Inorder(T->Lchild);
printf("%c",T->data);
Inorder(T->Rchild);
}
}
//后序遍历(左 右 根)
void Postorder(BiTree T){
if(T){
Postorder(T->Lchild);
Postorder(T->Rchild);
printf("%c",T->data);
}
}
/*
A
/ \
B #
/ \
C D
/ \ / \
# # E F
/ \ / \
# G # #
/ \
# #
以先序遍历的形式输入:ABC##DE#G##F###
*/
void main(){
BiTree T;
printf("create a tree such as abc##de#g##f###\n");
createbt(T);
printf("\n/*先序遍历*/");
Preorder(T);
printf("\n/*中序遍历*/");
Inorder(T);
printf("\n/*后序遍历*/");
Postorder(T);
}