1

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

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; 
} 

回答

1

你得到一个分段错误,因为你永远不设置头,还有当你站上罚球线

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

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

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

此外,您的代码有错误,因为new_node不返回值。