C++二进制搜索树的实现
C++ Binary Search Tree Implementation
我正在C++中进行一个项目,在该项目中,我必须创建一个二进制搜索树,插入数组中的项。我必须使用以下插入算法:
树插入(T,z)
y = NIL
x = T.root
while x != NIL
y = x
if z.key < x.key
x = x.left
else x = x.right
z.p = y
if y == NIL
T.root = z
else if z.key < y.key
y.left = z
else y.right = z
以下是我目前所拥有的:
#include <iostream>
using namespace std;
struct node
{
int key;
node* left;
node* right;
node* p;
node* root;
};
void insert(node*, node*);
void printinorder(node*);
int main()
{
node *root;
node* tree = new node;
node* z = new node;
int array [10] = {30, 10, 45, 38, 20, 50, 25, 33, 8, 12};
for (int i = 0; i < 10; i++)
{
z->key = array[i];
insert(tree, z);
}
printinorder(tree);
return 0;
}
void insert(node *T, node *z)
{
node *y = nullptr;
node* x = new node;
x = T->root;
while (x != NULL)
{
y = x;
if (z->key < x->key)
x = x->left;
else
x = x->right;
}
z->p = y;
if (y == NULL)
T->root = z;
else if (z->key < y->key)
y->left = z;
else
y->right = z;
}
void printinorder(node *x)
{
if (x != NULL)
{
printinorder(x->left);
cout << x->key << endl;
printinorder(x->right);
}
}
然而,当我运行这段代码时,它会编译错误。我相信这个问题与我正在创建的节点或我的函数调用有关。谢谢你的帮助。
除了注释中提到的问题外,这段代码中最大的错误是缺少一个构造函数,该构造函数将新node
中的所有指针初始化为NULL。
因此,您创建的每个node
的指针都包含随机垃圾。您的代码初始化了其中的一些,但大多数不是。尝试使用未初始化的指针将导致立即崩溃。
您需要修复注释中提到的所有问题,并为node
类提供一个合适的构造函数。
相关文章:
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 二叉搜索树 - 实现"search"函数
- 二叉搜索树的 C++ 实现中的EXC_BAD_ACCESS错误
- C++二叉搜索树实现不会添加每个元素
- 在C++中实现二叉搜索树,搜索不起作用.尝试打印节点的元素会导致输出崩溃
- C++二叉搜索树实现,动态数组或结构/类
- 二进制搜索树的数组实现
- 二叉搜索树实现C++运行时错误
- C++ 中字符串实现的二叉搜索树
- 二叉搜索树在C++中的实现
- C++二进制搜索树的实现
- 在 Java 中实现从预序数组重建二叉搜索树
- 它使用什么样的二进制搜索树来实现“std::set”
- 在我的二叉搜索树实现中找不到指针错误?
- 2-3搜索树在c++中的实现
- 二叉搜索树实现.编译的问题
- 使用模板和unique_ptr实现的二叉搜索树中返回具有最小值的节点
- 用栈实现二叉搜索树的非递归析构
- 二叉搜索树实现(c++)
- 二叉搜索树插入实现