二叉樹問題,根據先序序列輸入字符,然後輸出其先序遍歷,中序遍歷,後序遍歷。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree
{
char data;
struct tree *left, *right; //二叉樹左孩子,右孩子
}tree; //定義二叉樹
int cnt;
char st[55];
tree *creat();
void zhongxu(tree *root); //中序遍歷
void xianxu(tree *root); //先序遍歷
void houxu(tree *root); //後序遍歷
int main()
{
while(~scanf("%s", st))
{
cnt = -1;
tree *root; //定義根節點
root = creat();
xianxu(root);
printf("\n");
zhongxu(root);
printf("\n");
houxu(root);
printf("\n");
}
}
tree *creat()
{
tree *root;
if(st[++cnt] == ',')
{
root = NULL;
} //如果讀到‘,’,則爲空節點
else
{
root = (tree*)malloc(sizeof(tree));
root -> data = st[cnt];
root -> left = creat();
root -> right = creat();
}
return root;
}
void xianxu(tree *root)
{
if(root)
{
printf("%c", root -> data);
xianxu(root -> left);
xianxu(root -> right);
}
}
void zhongxu(tree *root)
{
if(root)
{
zhongxu(root -> left);
printf("%c", root -> data);
zhongxu(root -> right);
}
}
void houxu(tree *root)
{
if(root)
{
houxu(root -> left);
houxu(root -> right);
printf("%c", root -> data);
}
}