//二叉树的基本操作
//递归实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//二叉树的二叉链表存储表示
//二叉树的定义
typedef char TElemType;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild;
struct BiTNode *rchild;
} BiTNode,*BiTree;
//二叉树的建立 先序构造
int cnt;
char str[100]; //结点上没有数据的用其他
BiTree CreateBiTree() //符号代替,出现这种符号时
{
//把树的节点的值赋为空
BiTree T; //先给树的各节点开空间
//再为它赋值;再依次建立左子树与右子树
if(str[cnt]== ',') //建树的时候,一个结点一个结点的建立
{
T = NULL;
cnt++; //每次进来一个字符作为结点的值
}
else
{
T = (BiTree)malloc(sizeof(BiTNode));
T->data = str[cnt];
cnt++;
T->lchild = CreateBiTree();
T->rchild = CreateBiTree();
}
return T;
}
//先序遍历二叉树 //先判断树是否为空
void PreOrderBiTree(BiTNode * T) //不为空的话就按次序
{
//执行输出结点与
if(T != NULL) //遍历子树
{
printf("%c",T->data);
PreOrderBiTree(T->lchild);
PreOrderBiTree(T->rchild);
}
}
//中序遍历二叉树
void InOrderBiTree(BiTNode * T)
{
if(T!=NULL)
{
InOrderBiTree(T->lchild);
printf("%c",T->data);
InOrderBiTree(T->rchild);
}
}
//后序遍历二叉树
void PostOrderBiTree(BiTNode * T)
{
if(T != NULL)
{
PostOrderBiTree(T->lchild);
PostOrderBiTree(T->rchild);
printf("%c",T->data);
}
}
//求二叉树的深度
int BiTreeDepth(BiTNode * T)
{
int Depth,ldepth,rdepth;
if(T == NULL)
Depth = 0;
else
{
ldepth = BiTreeDepth(T->lchild);
rdepth = BiTreeDepth(T->rchild);
Depth = 1+(ldepth > rdepth ? ldepth : rdepth);
}
return Depth;
}
//求叶结点的个数
int CountLeaf(BiTNode * T)
{
int m,n;
if(T == NULL)
{
return 0;
}
if(T->lchild == NULL&&T->rchild == NULL)
{
return 1;
}
else
{
m = CountLeaf(T->lchild);
n = CountLeaf(T->rchild);
return (m + n);
}
return 0;
}
//求叶结点个数2
/*int CountLeaf(BiTNode * T)
{
int count = 0;
if(T == NULL) return 0;
else
{
if(T->lchild == NULL&&T->rchild == NULL)
{
count++;
}
CountLeaf(T->lchild);
CountLeaf(T->rchild);
}
return count;
}
*/
//查询二叉树中某结点
TElemType FindBiTree(BiTNode * T,char ch)
{
char a[30],b[30];
strcpy(a,"TRUE");
strcpy(b,"FALSE");
if(T == NULL)
return b[30];
else
{
if(T->data == ch)
{
return a[30];
}
else
{
FindBiTree(T->lchild,ch);
FindBiTree(T->rchild,ch);
}
}
return b[30];
}
void CengTravel(BiTree T)//非队列
{
BiTree temp[100];
int par = 0,chi = 1;
temp[par] = T; //不能只将T的data赋给temp,不然指针会乱掉
while(temp[par] != NULL)
{
printf("%c",temp[par]->data);
if(temp[par]->lchild != NULL)
{
temp[chi] = temp[par]->lchild;//->data //temp存的是树的结点
chi++;
}
if(temp[par]->rchild != NULL)
{
temp[chi] = temp[par]->rchild;
chi++;
}
par++;
if(par == chi)
break;
}
printf("\n");
}
void CengTravel(BiTree root,LinkQueue * Q)//队列实现层序遍历
{
EnQueue(Q,root);
// printf("%c",Q->front->next->T->data);
QueuePtr p;
while(Q->front->next!=NULL)
{
p = Q->front->next;
printf("%c",p->T->data);
if(p->T->lchild != NULL)
{
EnQueue(Q,p->T->lchild);
}
if(p->T->rchild != NULL)
{
EnQueue(Q,p->T->rchild);
}
DeQueue(Q);
}
printf("\n");
}
int main(){ while(scanf("%s",str)!=EOF) { BiTree T; cnt = 0; T = CreateBiTree(); //PreOrderBiTree(&T); InOrderBiTree(T); printf("\n"); PostOrderBiTree(T); printf("\n"); } return 0;}