遍历二叉树应用

void CountLeaf(BiTree &T,int &count){
if(T){
if((!T->lchild)&&(!T->rchild))
count++;
CountLeaf(T->lchild,count);
CountLeaf(T->rchild,count);
}
}

1.统计二叉树叶子节点的个数(先序遍历)

int Depth(BiTree T){
if(!T)
depthval=0;
else{
depthLeft=Depth(T->lchild);
depthRight=Depth(T->rchild);
depthval=1+(depthLeft>depthRighth?depthLeft:depthRight);
}
return depthval;}

2.求二叉树深度(后序遍历)

BiTNode *GetTreeNode(TElemType item,BiTNode *lptr,BiTNode *rptr){
if(!(T=(BiTNode*)malloc(sizeof(BiTnode))))exit(1);
T->data=item;
T->lchild=T->rchild;
return T;
}//生成一个二叉树的结点。
Status CopyTree(BiTNode *T){
if(!T)
return NULL;
if(T->lchild)
newlptr=CopyTree(T->lchild);
else newlptr=NULL;
if(T->rchild)
newrptr=CopyTree(T->rchild);
else newrptr=NULL;
newnode=GetTreeNode(T->data,newlptr,newrptr);
return newnode;
}

3.复制二叉树(后序遍历)

4.建立二叉树的存储结构

Status CreateBiTree(BiTree &T){
scanf(&ch);
if(ch==' ')}T=NULL:
esle{
if(!(T=(BiTNode*)malloc(sizeof(BiTNode))))exit(OVERFLOW);
T->data=ch;
CreateBitree(T->lchild);
CreateBitree(T->rchild);
}
renturn OK;
}

按给定的先序序列建立二叉树链表

void CrtExptree(BiTree &T,char exp[]){
InitStack(S);Push(S,'#');InitStack(PTR);
p=exp;ch=*p;
while(!(GetTop(S)=='#'&&ch=='#')){
if(!IN(ch,OP))CrtNode(t,ch);//建立叶子节点并入栈
else{
swith(ch){
case'(':Push(S,ch);break;
case‘)':Pop(S,c);
while(c!='('){
CrtSubtree(t,c);Pop(S,c);}break; 
default:
while(!Gettop(S,c)&&(precede(c,ch))){
CrtSubtree(t,c);
Pop(S,c);}
if(ch!='#')Push(S,ch);break}}
if(ch!='#'){p++;ch=*p}
}
Pop(PTR,T);}

按给定表达式建相应二叉树

其中建叶子结点的算法为:

void CrtNode(BiTree &T,char ch){
T->(BiTNOde*)malloc(sizeof(BiTNode));
T-data=char;
T-lchild=T->rchild=Null;
Push(PTR,T);}

建子树的算法为:

void CrtSubtree(Bitree&T,char c){
T-(BiTNode*)malloc(sizeof(BiTNode));
T->data=c;
Pop(PTR,rc);T->rchild=rc;
POp(PTR,lc);T->lchild=lc;
PUsh(PTR,T);}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值