#include <stdio.h>
#include<math.h>
#include<stdlib.h>
#define ok 1
#define false 0
struct treenode
{
char data;
treenode* left;
treenode* right;
};
typedef int status;
typedef treenode* Tree;
int main()
{
status creat(Tree & T);
status Preorder(Tree T);
status Inorder(Tree T);
status Postorder(Tree T);
status exchange(Tree & T);
printf("请按先序的顺序输入(#为空):");
Tree T;
creat(T);
printf("先序输出:");
Preorder(T);
printf("\n中序输出:");
Inorder(T);
printf("\n后序输出:");
Postorder(T);
exchange(T);
printf("\n将左右子树交换");
printf("\n先序输出:");
Preorder(T);
printf("\n中序输出:");
Inorder(T);
printf("\n后序输出:");
Postorder(T);
}
//先序建树
status creat(Tree& T)
{
char a;
scanf_s("%c", &a);
if (a == '#')//#为空节点
{
T = NULL;
return ok;
}
else
{
T = (treenode*)malloc(sizeof(treenode));
if (!T)
return OVERFLOW;
T->data = a;
creat(T->left);
creat(T->right);
}
return ok;
}
//先序遍历
status Preorder(Tree T)
{
if (T == NULL)
return ok;
else
{
printf("%c", T->data);
Preorder(T->left);
Preorder(T->right);
}
return ok;
}
//中序遍历
status Inorder(Tree T)
{
if (T == NULL)
return ok;
else
{
Inorder(T->left);
printf("%c", T->data);
Inorder(T->right);
}
return ok;
}
//后序遍历
status Postorder(Tree T)
{
if (T == NULL)
return ok;
else
{
Postorder(T->left);
Postorder(T->right);
printf("%c", T->data);
}
return ok;
}
//左右子树交换
status exchange(Tree& T)
{
treenode* temp;
if (T == NULL)
return ok;
else
{
temp = T->left;
T->left = T->right;
T->right = temp;
exchange(T->left);
exchange(T->right);
}
return ok;
}
调试结果