第5章 树与二叉树
5.3 二叉树的遍历和线索二叉树
综合应用题 第5题
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define MaxSize 100
using namespace std;
typedef int ElemType;
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct{
BiTNode* queue[MaxSize];
int front,rear;
}SqQueue;
void InitQueue(SqQueue &Q)
{
Q.rear=Q.front=-1;
}
int EnQueuel(SqQueue &Q,BiTNode* x)
{
if(Q.rear==MaxSize)
return 0;
Q.queue[Q.rear]=x;
Q.rear++;
return 1;
}
BiTNode* DeQueuel(SqQueue &Q)
{
BiTNode* x;
if(Q.front==Q.rear)
return 0;
x=Q.queue[Q.front];
Q.front++;
return x;
}
bool QueueEmpty(SqQueue &Q)
{
if(Q.front==Q.rear)
return true;
else
return false;
}
typedef struct {
BiTNode* stack[MaxSize];
int top;
}SqStack;
bool InitBiTree(BiTree &B){
B=NULL;
return true;
}
BiTree BiTreeCreatT(ElemType *a,BiTree &B) {
InitBiTree(B);
B=(BiTree)malloc(sizeof(BiTNode));
B->lchild=NULL;
B->rchild=NULL;
B->data=a[0];
BiTNode *p,*s;
s=B;
p = (BiTNode *)malloc(sizeof(BiTNode));
p->data = a[1];
p->lchild=NULL;
p->rchild=NULL;
s->lchild=p;
p = (BiTNode *)malloc(sizeof(BiTNode));
p->data = a[2];
p->lchild=NULL;
p->rchild=NULL;
s->rchild=p;
s=s->lchild;
p = (BiTNode *)malloc(sizeof(BiTNode));
p->data = a[3];
p->lchild=NULL;
p->rchild=NULL;
s->lchild=p;
p = (BiTNode *)malloc(sizeof(BiTNode));
p->data = a[4];
p->lchild=NULL;
p->rchild=NULL;
s->rchild=p;
return B;
}
int Btdepth(BiTree &B,SqQueue &Q)
{
BiTNode *s=B;
if(!s)
return 0;
else
{
int h=0,last=0;
EnQueuel(Q,s);
while(!QueueEmpty(Q))
{
s=DeQueuel(Q);
if(s->lchild)
EnQueuel(Q,s->lchild);
if(s->rchild)
EnQueuel(Q,s->rchild);
if(Q.front==last)
{
h++;
last=Q.rear;
}
}
return h;
}
}
int main() {
int a[5]={4,2,5,1,3};
BiTree B;
BiTreeCreatT(a,B);
SqQueue Q;
InitQueue(Q);
cout<<"树高:";
cout<<Btdepth(B,Q);
return 0;
}