C++二进制搜索树的实现

C++ Binary Search Tree Implementation

本文关键字:实现 搜索树 二进制 C++      更新时间:2023-10-16

我正在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类提供一个合适的构造函数。