如何解决在 C++ 中实现查找二叉树最小值的方法时出错分段错误
最后附上我的代码。我用 C++ 写的
我使用自定义类 Node 和 BinarySearchTree 实现了一个二元“搜索”树。方法插入,查找,所有深度优先遍历都按预期提供输出。如果我排除代码
,查找树高度的方法给出了分段错误(核心转储)错误if (root == nullptr)
return -1;
但预期的行为是给我正确的输出(树的高度),因为当 BinarysearchTree 对象(此处为“树”)为空时,上面的代码对应于单个边缘情况。 如果我包含该特定代码,则输出符合预期,没有错误。
同样,对于查找树的最小值的方法(我使用实现来查找任何二叉树的最小值,而不仅仅是故意的二叉搜索树),我得到了相同的分割故障(核心转储) 错误。当我尝试包含上面的代码(我认为这只是一个边缘情况)时,我的输出是该代码的返回值(此处为“-1”),如果此返回值小于树中的所有值。>
我需要这方面的帮助,因为我不知道我哪里出错了。
我的代码:
#include <iostream>
#include <algorithm>
class Node
{
public:
int value;
Node *leftChild;
Node *rightChild;
Node(int value)
{
this->value = value;
leftChild = rightChild = nullptr;
}
};
class BinarySearchTree
{
Node *root;
void traverseInorder(Node *root)
{
if (root == nullptr)
return;
traverseInorder(root->leftChild);
std::cout << root->value << " ";
traverseInorder(root->rightChild);
}
int height(Node *root)
{
// if (root == nullptr)
// return -1;
// checking if root is a leaf node
if ((root->leftChild == nullptr) && (root->rightChild == nullptr))
return 0;
return (1 + std::max(height(root->leftChild),height(root->rightChild)));
}
int minimum(Node *root)
{
// if (root == nullptr)
// return -1;
// checking if root is a leaf node
if ((root->leftChild == nullptr) && (root->rightChild == nullptr))
return root->value;
return std::min({minimum(root->leftChild),minimum(root->rightChild),root->value});
}
public:
BinarySearchTree()
{
root = nullptr;
}
void insert(int value)
{
Node *node = new Node(value);
if (root == nullptr)
{
root = node;
return;
}
Node *current = root;
while (1)
{
if (value < current->value)
{
if (current->leftChild == nullptr)
{
current->leftChild = node;
return;
}
current = current->leftChild;
}
else
{
if (current->rightChild == nullptr)
{
current->rightChild = node;
return;
}
current = current->rightChild;
}
}
}
bool find(int value)
{
Node *current = root;
while (current != nullptr)
{
if (value < current->value)
current = current->leftChild;
else if (value > current->value)
current = current->rightChild;
else
return 1;
}
return 0;
}
void traverseInorder()
{
traverseInorder(root);
std::cout << std::endl;
}
int height()
{
return height(root);
}
int minimum()
{
return minimum(root);
}
};
int main()
{
BinarySearchTree tree;
tree.insert(12);
tree.insert(16);
tree.insert(4);
tree.insert(10);
tree.insert(25);
tree.insert(3);
tree.insert(30);
tree.insert(23);
tree.traverseInorder();
std::cout << tree.height() << std::endl;
std::cout << tree.minimum() << std::endl;
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。