Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在二进制搜索树中插入值_C++_Data Structures_Linked List_Binary Tree_Binary Search Tree - Fatal编程技术网

C++ 在二进制搜索树中插入值

C++ 在二进制搜索树中插入值,c++,data-structures,linked-list,binary-tree,binary-search-tree,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

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

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;
}
struct节点
{
int数据;
节点*leftN;
节点*right;
};
typedef节点*Node_ptr;
节点头;
//插入值函数
节点*新节点(int键)
{
Node*leaf=新节点;
叶->数据=键;
leaf->leftN=NULL;
leaf->rightN=NULL;
}
节点*插入值(节点ptr叶,int键)
{
if(leaf==NULL)
返回(新_节点(键));
其他的
{
if(关键数据)
leaf->leftN=插入_值(leaf->leftN,键);
其他的
leaf->rightN=插入_值(leaf->rightN,键);
返回(叶);
}
}
//打印功能
无效打印树(节点\u ptr叶)
{
if(leaf==NULL)
返回;
打印树(叶->左);

cout你会遇到分段错误,因为当你到达终点线时,你从来没有设置头部

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

cout你遇到了一个分段错误,因为当你到达终点线时,你从来没有设置头部

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