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입니다 (NULL로 설정된 head 값으로 설정 되었기 때문에).

일반적으로 "루트"(또는 "헤드") 노드는 특별한 경우 시나리오이므로 노드가 insert_value의 맨 위에 구성되었는지 확인하고, 그렇지 않으면 노드 노드를 다음과 같이 지정해야합니다. 그것.

또한 코드에 오류가 있습니다. new_node은 값을 반환하지 않습니다.

관련 문제