在C ++中实现BST时遇到问题。当我向BST插入大约20,000个数据的小数据时,它运行良好。如果我尝试在100,000左右插入大量数据。 BST收到运行时错误。你能帮助我吗?
这是我的实施。 Binary Search.h
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
struct treeNode
{
long long data;
treeNode *left;
treeNode *right;
};
treeNode *insertNode(treeNode *node,long long data)
{
if(node==NULL)
{
treeNode *temp = new treeNode;
//temp = (treeNode *)malloc(sizeof(treeNode));
temp -> data = data;
temp -> left = temp -> right = NULL;
return temp;
}
if(data >(node->data))
{
node->right = insertNode(node->right,data);
}
else if(data < (node->data))
{
node->left = insertNode(node->left,data);
}
/* Else there is nothing to do as the data is already in the tree. */
return node;
}
treeNode * searchNode(treeNode *node, long long data)
{
if(node==NULL)
{
/* Element is not found */
return NULL;
}
if(data > node->data)
{
/* Search in the right sub tree. */
return searchNode(node->right,data);
}
else if(data < node->data)
{
/* Search in the left sub tree. */
return searchNode(node->left,data);
}
else
{
/* Element Found */
return node;
}
}
void displayInorder(treeNode *node)
{
if(node==NULL)
{
return;
}
displayInorder(node->left);
cout<<" " << node->data<<" ";
displayInorder(node->right);
}
void displayPreorder(treeNode *node)
{
if(node==NULL)
{
return;
}
cout<<" " <<node->data<<" ";
displayPreorder(node->left);
displayPreorder(node->right);
}
void displayPostorder(treeNode *node)
{
if(node==NULL)
{
return;
}
displayPostorder(node->left);
displayPostorder(node->right);
cout<<" " <<node->data<<" ";
}
我在以下位置收到运行时错误:
node->right = insertNode(node->right,data);
请帮帮我们。
提前谢谢!
答案 0 :(得分:0)
您可能会在所有递归中耗尽堆栈,因此您可以增加堆栈,或者编写一些(或全部)函数以使用迭代而不是递归(尽管预订,后序,顺序遍历)难以正确地写为循环)。
以下是Search
和Insert
方法的简单示例:
struct TreeNode
{
long long data = 0;
std::shared_ptr<TreeNode> left;
std::shared_ptr<TreeNode> right;
TreeNode(long long _data) : data(_data){}
};
class BST
{
public:
void Insert(std::shared_ptr<TreeNode> node)
{
if (!node)
throw std::runtime_error("Cannot insert null node");
if (!root)
{
root = node;
return;
}
std::shared_ptr<TreeNode>* next = &root;
while(*next)
{
if (node->data < (*next)->data)
next = &((*next)->left);
else
next = &((*next)->right);
}
*next = node;
}
std::pair<bool, std::shared_ptr<TreeNode>> Search(long long data)
{
if (!root)
return std::make_pair(false, nullptr); // searching empty tree
std::shared_ptr<TreeNode> next = root;
while(next)
{
if (data < next->data)
next = next->left;
else if (data > next->data)
next = next->right;
else
return std::make_pair(true, next); // match found
}
// no match found
return std::make_pair(false, nullptr);
}
private:
std::shared_ptr<TreeNode> root;
};
可以找到完整的工作演示here