繁体   English   中英

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类提供适当的构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM