此函數遞歸調用自身以搜索Btree,如果找到該值,則返回true;如果未找到,則返回false。如果找不到,我也希望它在最後一次找到「未找到」。它可以正常工作,只是它會自動調用「無法找到」多次(每次它找不到的級別)。B樹遞歸搜索C++
bool lookup(int val, btnode *n) //returns true/false if value is in btree
{
if (n==NULL) return false; //empty tree
for (int i=0;i< n->count;i++) //check in present node for the val
if(n->value[i]==val)
{
flag = true;
return true;
}
//check in child node
for(int i =0;i<n->count;i++) //check for child node
{ if(val < n->value[i])
{ cout<<"checking a different node."<<endl;
lookup(val,n->child[i]);
}
}
if(val > n->value[(n->count)-1])
{
cout<<"searching a right subtree"<<endl;
lookup(val, n->child[n->count]);
}
if (flag==false)
return false;
else return true;
}
bool lookup2(int val, btnode *n)
{
if(lookup(val, n)==false)
{
cout<<"not found"<<endl;
return false;
}
else
{
cout<<"Found it"<<endl;
return true;
}
}
有兩個功能。實際打印的一個,以及您現在正在遞歸執行工作的那個。 – zz3599 2013-03-15 21:12:46
爲什麼不在調用者那裏做這件事,而不是試圖在這裏使用這種方法呢? – Tawnos 2013-03-15 21:13:26
另外一個'bool contains()'函數幾乎沒有比'location find()'更有用。 – 2013-03-15 21:18:15