二叉树的基本操作
#include <iostream>
using namespace std;
typedef struct tree1{
char data;
struct tree1 *lchild,*rchild;
int ltag,rtag;
}nodetree,*tree;
typedef struct Node {
tree data;
struct Node *next;
}Node, *pNode;
pNode p;
void InitQueue()
{
p = (struct Node *)malloc(sizeof(struct Node));
p->next = p;
}
void EnQueue(tree x)
{
pNode r,t=p;
r = (struct Node *)malloc(sizeof(struct Node));
r->data=x;
while(t->next!=p)
{
t=t->next;
}
t->next=r;
r->next=p;
}
int isEmpty()
{
if(p->next==p)
return 1;
else
return 0;
}
void DeQueue(tree &x)
{
pNode t=p->next;
x=t->data;
p->next=t->next;
free(t);
}
void createtree(tree &t) //二叉树的先序遍历创建
{
char ch;
cin>>ch;
if(ch!='@')
{
t=new nodetree;
t->data=ch;
createtree(t->lchild);
createtree(t->rchild);
}
else
t=NULL;
}
void show(tree &t) //二叉树的层序输出
{
InitQueue();
EnQueue(t);
tree x;
while(!isEmpty())
{
DeQueue(x);
printf("%c ",x->data);
if(x->lchild!=NULL)
EnQueue(x->lchild);
if(x->rchild!=NULL)
EnQueue(x->rchild);
}
printf("\n");
}
int showtree(tree &t) //二叉树是后序输出
{
if(t!=NULL)
{
showtree(t->lchild);
showtree(t->rchild);
cout<<t->data<<' ';
}
else
return 1;
}
int shendu(tree t)//求树的深度
{
if(t==NULL)
return 0;
else
return max(shendu(t->lchild),shendu(t->rchild))+1;
}
int yezi(tree t) //求树的叶子
{
if(t==NULL)
return 0;
if(t->lchild==NULL&&t->rchild==NULL)
return 1;
else
return yezi(t->lchild)+yezi(t->rchild);
}
void trecopy(tree &T1,tree &T2)//树的复制
{
if(T1 == NULL)
{
T2 = NULL;
return;
}else
{
T2 = new tree;
T2->data = T1->data;
trecopy(T1->lchild,T2->lchild);
trecopy(T1->rchild,T2->rchild);
}
}
int Countnode(tree T)//计算二叉树结点总数
{
if(T==NULL)
return 0;
else
return Countnode(T->lchild)+Countnode(T->rchild)+1;
}
int Num1(tree &T){ //统计度为1的节点的个数
if(T == NULL)
return 0;
if(T->lchild == NULL&&T->rchild != NULL)
{
return Num1(T->rchild)+1;
}
else if(T->lchild != NULL&&T->rchild == NULL)
{
return Num1(T->lchild)+1;
}
else
{
return Num1(T->rchild)+Num1(T->lchild);
}
}
int main()
{
tree t;
createtree(t);
showtree(t);
printf("\n");
show(t);
cout<<shendu(t)<<endl;
cout<<yezi(t)<<endl;
return 0;
}