2014-03-31 142 views
0

我在写一个带搜索功能的二叉树。该函数应该带有一个参数x,它表示要搜索的值,一旦找到该值,确定它是否为叶。如果未找到该值,则搜索功能将返回false。如何找到二叉树的叶子?

这是我给了我一个seg故障,并且只给了我1到100的每个值的虚假回报。二叉树是initalized与100个值。

bool search(Node<T>* &currentNode, 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>* &currentNode, const T& x) 
{ 

} 

bool leaf(Node<T>* currentNode) const 
{ 
    if (currentNode != nullptr) 
    { 
    return ((currentNode->left == nullptr && currentNode->right == nullptr) ? true : false);   
    } 
    else 
    { 
     return true; 
    } 
} 
+0

您在哪条线上遇到seg故障?您还假定二叉树是排序的(即,每个节点比左更大,更小或等于右)。你的函数是否接收到一个排序的二叉树? – CurlyCorvus

+0

我按值按降序插入元素。 – Scholar

+0

我的意思是[自我平衡树](https://en.wikipedia.org/wiki/Self-balancing_binary_search_tree)。无论哪种方式,如果x位于不是叶的节点上,该函数将永远不会找到它,因为它只能为叶节点返回true。这不是一个完整的答案,但是你应该有一部分函数读取'if(x == currentNode-> data)return true;'(因为你正在寻找值x)。你应该单独修改seg错误并要求算法而不是仅仅倾销代码。 – CurlyCorvus

回答

0

此外,当currentNodenullptr时,leaf函数返回true,假设检查nullptrsearch已解决。这是你想要的一个指针指向一个不存在的叶子的行为?

+0

如果左侧和右侧子元素都是空指针,则叶函数也会返回true。我用tenary操作符返回true或false。表达式可能有些错误,它永远不会返回true? – Scholar

+0

@Revoo我发现它的方式是在'search'函数中应该有两个基本情况,否则会出现问题。他们两人已经在评论和回复帖子之间被提及。在更新代码,测试代码并随后更新问题详细信息之后,我们其他人可能需要审查和帮助。 –

0

在你的搜索功能,你的子节点上没有追索权,如果他们nullptr第一...然后尝试去仍引用数据元素,不检查空看。