二叉树的基本操作

二叉树的基本操作

#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;
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值