#include <bits/stdc++.h>
#define MaxSize 100
/*
* Created by HarvestWu on 2018/07/18.
*/
using namespace std;
typedef char ElemType;
//定义二叉树结构
typedef struct BTNode
{
ElemType data;
struct BTNode *lchild;
struct BTNode *rchild;
} BTNode;
//由先序遍历、中序遍历结果构建二叉树
BTNode *CreateBT(ElemType pre[],ElemType in[],int l1,int r1,int l2,int r2)
{
BTNode *s;
int i;
if(l1>r1)return NULL; //序列中无元素返回NULL
s=(BTNode*)malloc(sizeof(BTNode));
s->lchild=s->rchild=NULL;
for(i=l2; i<=r2; ++i)
if(in[i]==pre[l1]) //查找等于当前子树根的结点在in[]中的位置
break;
s->data=in[i];
s->lchild=CreateBT(pre,in,l1+1,l1+i-l2,l2,i-1);
s->rchild=CreateBT(pre,in,l1+i-l2+1,r1,i+1,r2);
return s; //当前子树处理完毕
}
//判定值为x的结点的层号
int L=1;//记录层号
void leno(BTNode *p,ElemType x)
{
if(p!=NULL)
{
if(p->data==x)
cout<<L<<endl;
++L; //进入下一层
leno(p->lchild,x);
leno(p->rchild,x);
--L; //返回上一层
}
}
int main()
{
BTNode *p,*head,*tail;
ElemType pre[]= {'A','B','D','E','H','J','K','L','M','N','C','F','G','I'};
ElemType in[]={'D','B','J','H','L','K','M','N','E','A','F','C','G','I'};
//由先序遍历、中序遍历结果构建二叉树
p=CreateBT(pre,in,0,13,0,13);
ElemType x;
while(cin>>x)
leno(p,x);
return 0;
}
C++ 判定值为x的结点的层号
猜你喜欢
转载自blog.csdn.net/harvestwu/article/details/81102916
今日推荐
周排行