#include <stdio.h>
#include <stdlib.h>
typedef struct BiNode
{
char data;
struct BiNode *lchild, *rchild;
}BiNode, *BiTree;
void CreateBiTree(BiTree &T);
void PreOrderTraverse(BiTree T);
void InOrderTraverse(BiTree T);
void PostOrderTraverse(BiTree T);
int CountLeaf(BiTree T);
int CalcHight(BiTree T);
void exchange(BiTree T);
void GetSubHight(BiTree T, char x);
void DelSubTree(BiTree T, char x);
void DelTree(BiTree T);
int main(int argc, char *argv[])
{
BiTree T;
printf("创建二叉树--->\n");
printf("请输入一串字符,三个空格为结束符\n");
printf("例:1 2 3 4 5 6 \n");
CreateBiTree(T);
getchar();
printf("先序遍历--->");
PreOrderTraverse(T);
printf("\n");
printf("中序遍历--->");
InOrderTraverse(T);
printf("\n");
printf("后序遍历--->");
PostOrderTraverse(T);
printf("\n");
printf("叶子的个数为--->%d\n",CountLeaf(T));
printf("树的深度为--->%d\n", CalcHight(T));
printf("交换左右子树--->\n");
exchange(T);
printf("中序遍历--->");
InOrderTraverse(T);
printf("\n");
printf("以'3'为根节点的子树的深度为--->");
GetSubHight(T, '3');
printf("删除以'7'为根节点的子树--->\n");
DelSubTree(T, '7'); /这个地方有问题呀。。。。
//
printf("后序遍历--->");
//
PostOrderTraverse(T);
printf("\n");
system("PAUSE");
return 0;
}
void CreateBiTree(BiTree &T)
{
char c;
if((c = getchar()) == ' ')
T = NULL;
else
{
T = (BiNode *)malloc(sizeof(BiNode));
if(!T)
{
perror("malloc failed!\n");
exit(1);
}
T->data = c;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void PreOrderTraverse(BiTree T)
{
if(T)
{
printf("%c", T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
void InOrderTraverse(BiTree T)
{
if(T)
{
InOrderTraverse(T->lchild);
printf("%c", T->data);
InOrderTraverse(T->rchild);
}
}
void PostOrderTraverse(BiTree T)
{
if(T)
{
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
printf("%c", T->data);
}
}
//统计二叉树中叶子节点的个数
int CountLeaf(BiTree T)
{
if (!T)
{
return 0;
}
if (!T->lchild && !T->rchild )
{
return 1;
}
else
{
return CountLeaf(T->lchild)+CountLeaf(T->rchild);
}
}
//统计二叉树的深度
int CalcHight(BiTree T)
{
int h, h1, h2;
if (!T)
{
return 0;
}
else
{
h1 = CalcHight(T->lchild);
h2 = CalcHight(T->rchild);
h = (h1>=h2 ? h1+1 : h2+1);
return h;
}
}
//将二叉树中所有节点的左右子树交换
void exchange(BiTree T)
{
BiTree temp;
temp = T->lchild;
T->lchild = T->rchild;
T->rchild = temp;
if (T->lchild)
{
exchange(T->lchild);
}
if (T->rchild)
{
exchange(T->rchild);
}
}
//求二叉树中以值x为根的树的深度
void GetSubHight(BiTree T, char x)
{
if (T->data == x)
{
printf("%d\n", CalcHight(T));
}
else
{
if (T->lchild)
{
GetSubHight(T->lchild, x);
}
if (T->rchild)
{
GetSubHight(T->rchild, x);
}
}
}
//删除以值x为根节点的子树
void DelSubTree(BiTree T, char x)
{
if (T->data == x)
{
DelTree(T);
}
else
{
if (T->lchild)
{
DelSubTree(T->lchild, x);
}
if (T->rchild)
{
DelSubTree(T->rchild, x);
}
}
}
//删除树
void DelTree(BiTree T)
{
if (T->lchild)
{
DelTree(T->lchild);
}
if (T->rchild)
{
DelTree(T->rchild);
}
free(T);
}