검색 기능이있는 이진 트리를 작성했습니다. 이 함수는 검색 할 값을 나타내는 인자 x를 취해서 발견되면 잎인지 아닌지를 결정합니다. 값을 찾을 수 없으면 검색 함수는 false를 반환합니다.이진 트리의 잎을 찾는 방법은 무엇입니까?
다음은 내가 seg 결함을 제공하며 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;
}
}
어떤 줄에서 세그 폴트가 발생합니까? 또한 이진 트리가 정렬되어 있다고 가정합니다 (즉, 각 노드는 왼쪽보다 크거나 작거나 같음). 함수가 정렬 된 이진 트리를 받습니까? – CurlyCorvus
요소를 값순으로 내림차순으로 삽입합니다. – Scholar
나는 [self balancing tree] (https://en.wikipedia.org/wiki/Self-balancing_binary_search_tree)를 의미했습니다. 어느 쪽이든, x가 잎이 아닌 노드에 있으면 잎 노드에 대해서만 참을 반환 할 수 있기 때문에 함수는 그것을 찾지 못한다. 이것은 완전한 대답은 아니지만 'if (x == currentNode-> data)가 true를 반환하는 함수의 일부분을 가져야합니다.'(값 x를 검색하므로) seg 오류를 일으키고 코드를 덤프하는 대신 알고리즘을 묻습니다. – CurlyCorvus