设计一个算法,求出指定结点在给定二叉排序树中的层次
#include <iostream>
#include <queue>
typedef struct node{
int data;
struct node* left;
struct node* right;
}node,*pnode;
pnode buynode(int x)
{
pnode tmp=(pnode) malloc(sizeof (node));
tmp->data=x;
tmp->left= nullptr,tmp->right= nullptr;
return tmp;
}
void build_tree(pnode &root,int data)
{
if(root== nullptr) {
root= buynode(data);
return;
}
if(data<root->data)build_tree(root->left,data);
if(data==root->data) return;
if(data>root->data) build_tree(root->right,data);
}
void print(pnode root)
{
if(root== nullptr) return;
std::queue<pnode> record;
record.push(root);
int size=record.size();
while(!record.empty()){
pnode head=record.front();
printf("%3d",head->data);
record.pop();
if(head->left) record.push(head->left);
if(head->right) record.push(head->right);
if(--size==0) puts(""),size=record.size();
}
}
int find_layer(pnode root,int x)
{
int n=0;
pnode tmp=root;
if(tmp) n++;
while(tmp&&tmp->data!=x){
if(tmp->data>x) tmp=tmp->left;
else tmp=tmp->right;
n++;
}
if(!tmp) return -1;//没找到
else return n;
}
int main() {
pnode r1= nullptr;
//p295图7.8(a),这是一棵二叉排序树
int a[]={45,24,12,37,28,40,55,53,60,70};
for(int i=0;i<10;i++)
{
build_tree(r1,a[i]);
}
print(r1);
for(int i=0;i<10;i++)
{
printf("the number %3d is in layer :%3d\n", a[i],find_layer(r1,a[i]));
}
printf("the number %3d is in layer :%3d\n", 1,find_layer(r1,1));//不存在
return 0;
}