c++ - 在二叉搜索树中插入值

标签 c++ data-structures linked-list binary-tree binary-search-tree

我正在尝试编写一种在二叉搜索树中设置值的方法。我已经实现了一种简单的递归技术来在树中添加节点。但是当我输入值并运行代码时,我遇到了段错误:

struct Node
{
    int data;
    Node* leftN;
    Node* rightN;

};

typedef Node* Node_ptr;
Node_ptr head;

//INSERT_VALUE FUNCTION
Node* new_node(int key)
{
    Node* leaf = new Node;
    leaf->data = key;
    leaf->leftN = NULL;
    leaf->rightN = NULL;
}
Node* insert_value(Node_ptr leaf, int key)
{
    if(leaf == NULL)
        return(new_node(key));
    else
    {
        if(key <= leaf->data)
            leaf->leftN = insert_value(leaf->leftN, key);
        else
            leaf->rightN = insert_value(leaf->rightN, key);
        return(leaf);   
    }
}

//PRINT FUNCTION
void printTree(Node_ptr leaf)
{
    if(leaf == NULL)
        return;
    printTree(leaf->leftN);
    cout << "Data element: " << leaf->data << endl;
    printTree(leaf->rightN);
}

//MAIN
int main()
{
    Node_ptr root = NULL;
    Node_ptr tail;
    int i;
    int x;

    //initialize values
    for(i = 0; i < 20; i++)
    {
        x = rand() % 1000 + 1;
        tail = insert_value(root, x);
            root = head;
    }

    root = head;
    printTree(root);

    root = head;
    cout << "Head Node: " << root->data << endl;

    return 0;
}

最佳答案

你遇到了段错误,因为你从来没有设置头部,当你到达线路时就在那里

cout << "Head Node: " << root->data << endl;

您的根值将为 NULL,(因为它被 head 设置为 NULL)。

“根”(或“头”)节点通常是一种特殊情况,您应该检查该节点是否已在 insert_value 的顶部构造,如果没有,则您将节点节点分配给它。

另外,您的代码中有错误,因为 new_node 没有返回值。

关于c++ - 在二叉搜索树中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10116198/

相关文章:

c++ - 如何在 CMake 中使用 OpenGL/Angle 编译 QtGui 示例?

c++ - 找到两对数字,使它们的乘积绝对差最小化

c++ - 理解realloc

C通用双链表每个节点持有多个项目

在链表中创建数据类型为 "struct"的新节点

c++ - 在类中使用 random 进行循环

flash - 需要非常大的数据结构。寻找想法

c# - 读一个文件,谁的行改变类型

java - 数据结构帮助 - 理解思维过程

c - 搜索项链表 C(队列)