数据结构作业之求叶子数,深度和二叉树的复制

数据结构作业,求叶子数,深度和二叉树的复制

#include <stdio.h>
#include <stdlib.h>
typedef struct binode
{
 char data;
 struct binode *lchild,*rchild;
}Binode,*Bitree;
typedef struct snode
{
 Bitree *data;
 int top;
}Stack;
int initstack(Stack *S)
{
 S->data=(Bitree *)malloc(sizeof(Bitree)*100);
 S->top=0;
 return 1;
}  
int enstack(Stack *S,Bitree e)
{
 S->data[S->top++]=e;
 return 1; 
}
Bitree destack(Stack *S)
{
 Bitree e;
 e=S->data[--S->top];
 return e;
}
void createBitree(Bitree &T)
{
 char ch;
 scanf("%c",&ch);
 if(ch!='#')
 {
  T=(Bitree)malloc(sizeof(Binode));
  T->data=ch;
  T->lchild=T->rchild=NULL;
  createBitree(T->lchild);
  createBitree(T->rchild);
 }
}

void copy(Bitree T,Bitree &P)
{
 Stack S;Bitree e,r,s;
 initstack(&S);
 enstack(&S,T);
 P=(Bitree)malloc(sizeof(Binode));
 P->data=T->data;
 P->lchild=P->rchild=NULL;
 s=P;
 while(S.top>0)
 {
  e=S.data[S.top-1];
  while(S.data[S.top-1]!=NULL)
  {
   enstack(&S,e->lchild);
   e=S.data[S.top-1];
   if(e!=NULL)
   {
   r=(Bitree)malloc(sizeof(Binode));
   r->data=e->data;
   r->lchild=r->rchild=NULL;
   s->lchild=r;
   s=r;
   }
   else
   s->lchild=NULL;
  }
  destack(&S);
  if(S.top>0)
  {
   e=destack(&S);
   enstack(&S,e->rchild);
   if(e->rchild!=NULL)
   {
   r=(Bitree)malloc(sizeof(Binode));
   r->data=e->rchild->data;
   r->lchild=r->rchild=NULL;
   s->rchild=r;
   s=r;
   }
   else
   s->rchild=NULL;
  }   
 }
}

void dispbitree(Bitree e)
{
 if(e)
 {
  printf("%c ",e->data);
  dispbitree(e->lchild);
  dispbitree(e->rchild);
 }
}
int leaf(Bitree T)
{
 if(T==NULL)
  return 0;
 if(T->lchild==NULL&&T->rchild==NULL)
  return 1;
 else
 {
  int m=leaf(T->lchild);
  int n=leaf(T->rchild);
  return (m+n);
 }
}

void leaf_2(Bitree T,int *count)
{
 if(T->lchild==NULL&&T->rchild==NULL)
  *count++;
 if(T->lchild) leaf_2(T->lchild,count);
 if(T->rchild) leaf_2(T->rchild,count);
}
int depth(Bitree T)
{
 int m,n;
 if(T==NULL)
  return 0;
 else
 {
  m=depth(T->lchild);
  n=depth(T->rchild);
  return (m>n? m:n)+1;
 }
}

void depth_2(Bitree T,int level,int *result)
{
 if(T)
 {
  if(level>*result)
   *result=level;
  depth_2(T->lchild,level+1,result);
  depth_2(T->rchild,level+1,result);
 } 
}

int main()
{
 Bitree T,P;
 createBitree(T);
 copy(T,P);
 dispbitree(P); 
 int result;
 depth_2(T,1,&result);
 printf("%d",result);
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值