[英]Recursive boolean function for a binary search tree
I have a class implementing binary search tree and one of my private methods is method bool find(Node<Key, Info> * &node, Key _key);
我有一个实现二进制搜索树的类,我的私有方法之一是方法
bool find(Node<Key, Info> * &node, Key _key);
, where node
stands for a pointer to a node, we start searching from and _key
stands for a unique for every node key. ,其中
node
代表指向node
的指针,我们从开始搜索, _key
代表每个节点键的唯一性。 My method is implemented as follows: 我的方法实现如下:
template<typename Key, typename Info>
bool BST<Key, Info>::find(Node<Key, Info>* &node, Key _key)
{
if (node)
{
if (node->key == _key)
{
return true;
}
else
{
find(node->left, _key);
find(node->right, _key);
return false;
}
}
else return false;
}
And it doesn't return true, even if the element with the given key exists. 即使存在具有给定键的元素,它也不会返回true。 I added a printing command just before return statement and it executes so my function seems to find the given node, but I guess my understanding is wrong and it still somehow returns false.
我在return语句之前添加了一条打印命令,该命令执行后,因此我的功能似乎找到了给定的节点,但是我想我的理解是错误的,并且仍然以某种方式返回false。
The solution to my problem seems to be found :) 解决我的问题的方法似乎是:)
template<typename Key, typename Info>
bool BST<Key, Info>::find(Node<Key, Info>* &node, Key _key)
{
if (node)
{
if (node->key == _key)
{
return true;
}
else if(_key<node->key)
return find(node->left, _key);
else
return find(node->right, _key);
}
else return false;
}
For binary search trees, you, of course, want to walk down the tree until you find the value or reach nullptr. 对于二叉搜索树,您当然要在树上走下来,直到找到该值或到达nullptr。 I'll write out a search function real quick here:
我将在此处快速写出搜索功能:
bool search(Node * node, int value){
if(node == nullptr) //If it's nullptr, we've reached the end without finding value.
return false;
if(node->value == value) //If it's value, we've found it!
return true;
if(node->value > value) //If value is less than node's value, go to left.
return search(node->left, value);
if(node->value < value) //If value is greater than node's value, go to right.
return search(node->right, value);
}
This is a recursive search for an organized tree (without using templates, for the sake of simplicity). 这是对有组织的树的递归搜索(为简单起见,不使用模板)。 Therefore, in a binary search tree, you first need to check if node is
nullptr
, then if it is value
, and then go from there. 因此,在二叉搜索树中,您首先需要检查node是否为
nullptr
,然后是否为value
,然后从那里开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.