题目:
我的代码实现:
#includeusing namespace std; #define TElemType int typedef struct BiTNode{ TElemType data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; void CreateBiTree(BiTree &T)//先序建立二叉链表 { int ch; cin>>ch; if(ch==-1)T=NULL; else { T=new BiTNode; T->data=ch; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } } //队列的存储结构定义及其操作....................... #define MAXQSIZE 100 #define QElemType BiTNode* typedef struct{ QElemType *base; int front; int rear; }SqQueue; bool InitQueue(SqQueue &Q) { Q.base=new QElemType[MAXQSIZE]; if(!Q.base)exit(EOVERFLOW); Q.front=Q.rear=0; return true; } int QueueLength(SqQueue Q) { return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE; } bool EnQueue(SqQueue &Q,QElemType e) { if((Q.rear+1)%MAXQSIZE==Q.front)return false; Q.base[Q.rear]=e; Q.rear=(Q.rear+1)%MAXQSIZE; return true; } bool DeQueue(SqQueue &Q,QElemType &e) { if(Q.front==Q.rear)return false; e=Q.base[Q.front]; Q.front=(Q.front+1)%MAXQSIZE; return true; } //................................... //本题的解答(层序遍历思想)................................. int h1=-1,h2=-1; void LocateTreeData(BiTree &T,int a,int b) { int h=1; SqQueue Q; QElemType e; InitQueue(Q);//初始化队列Q EnQueue(Q,T); while(Q.front!=Q.rear) { int l=QueueLength(Q);//计算此时队列的长度 while(l) { DeQueue(Q,e); if(e->data==a)h1=h; if(e->data==b)h2=h; l--; if(e->lchild)EnQueue(Q,e->lchild); if(e->rchild)EnQueue(Q,e->rchild); } h++; } if(h1==-1&&h2==-1)cout<<'n'<<-2< h2)cout<<'n'< lchild); DestroyTree(T->rchild); printf("销毁结点: %dn",T->data); delete T; T=NULL; } return; } int main() { BiTree T=NULL; printf("n构造二叉树:n"); CreateBiTree(T);//构造二叉树T int a,b; printf("指定两个整数:n"); cin>>a; cin>>b; LocateTreeData(T,a,b);//本题的解答 DestroyTree(T);//销毁二叉树 }
算法思想:本题的解法基于层序遍历的思想,具体的来说基于队列操作,将每层结点的指针放入队列再出来,然后对每层的结点中的数值逐个检查,顺带将下一层的结点指针入队,这样下去直到所有结点的指针都经历了入队和出队为止



