【发布时间】:2014-05-10 05:25:01
【问题描述】:
我正在编写具有搜索功能的二叉树。该函数应该接受一个参数 x ,它表示要搜索的值,一旦找到,确定它是否是叶子。如果未找到该值,则搜索函数返回 false。
这就是我所拥有的,它给了我一个段错误,并且一直给我从 1 到 100 的每个值的错误返回。二叉树初始化为 100 个值。
bool search(Node<T>* ¤tNode, const T& x) const
{
//~ cout << "CURRENT NODE DATA: " << currentNode->data << " : ";
/* FUNCTION: Searches for variable that is passed in X and checks if this value is a leaf or not */
//Left Subtree Search
if (x < currentNode->data)
{
if ((leaf(currentNode)) == true)
{
return true;
}
else
{
search(currentNode->left, x);
}
}
//Right Subtree Search
else if (x >= currentNode->data)
{
//If node in right subtree is a node check
if ((leaf(currentNode)) == true)
{
return true;
}
else
{
search(currentNode->right, x);
}
}
//Return false if the node is not a leaf
return false;
} //END OF SEARCH FUNCTION
void remove(Node<T>* ¤tNode, const T& x)
{
}
bool leaf(Node<T>* currentNode) const
{
if (currentNode != nullptr)
{
return ((currentNode->left == nullptr && currentNode->right == nullptr) ? true : false);
}
else
{
return true;
}
}
【问题讨论】:
-
您在哪一行遇到了段错误?您还假设二叉树已排序(即,每个节点都大于左侧,小于或等于右侧)。你的函数是否接收到排序的二叉树?
-
我按值降序插入元素。
-
我的意思是self balancing tree。无论哪种方式,如果 x 在不是叶子的节点上,该函数将永远找不到它,因为它只能为叶子节点返回 true。这不是一个完整的答案,但您应该拥有读取
if(x==currentNode->data) return true;的函数的某些部分(因为您正在搜索值x。)您可能应该单独修复段错误并询问算法,而不是仅仅转储代码.
标签: c++ pointers search recursion binary-tree