**算法思想:**求指定結點的層次也就是求指定結點的高度,理論上來說有好幾種方法,可以類比二叉樹求高度的算傳送門進行改造,或者直接根據二叉排序樹的查找來直接計算,下面給出直接根據二叉排序樹查找直接計算的方法
首先給出二叉排序樹的查找算法做一下借鑑
void BST_Search(BSTree *root,int k){
if(!root)
return;
while (root){
if(root->data==k){
cout<<"result: "<<root->data;
break;
}
else if(root->data>k){
cout<<"left-->";
root=root->lchild;
}
else{
cout<<"right-->";
root=root->rchild;
}
}
}
在查找算法上進行修改
int Level(BSTree *root,int k){
int height=0;
if(!root)
return 0;
while (root){
if(root->data==k){
height++;
break;
}
else if(root->data>k){
height++;
root=root->lchild;
}
else{
height++;
root=root->rchild;
}
}
return height;
}
也可以進行一些優化,此處就不寫了