정수 값을 포함하는 노드로 구성된 이진 트리와 노드의 왼쪽 및 오른쪽 분기에 대한 포인터.이진 트리의 루트에서 값을 인쇄하려고 할 때 크래시가 발생합니다.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node *left;
struct node *right;
} Node;
void insert(Node *root, int val);
int main(void){
Node *root = NULL;
insert(root, 5);
insert(root, 3);
printf("%d\n", root->val);
return 0;
}
void insert(Node *root, int val){
if(root == NULL){ // Create tree if root is empty
root = malloc(sizeof(struct node));
root->val = val;
root->left = NULL;
root->right = NULL;
} else if(val < root->val){ // branch to left of tree if new value is less than root value
if(root->left == NULL){
root->left = malloc(sizeof(struct node));
}
root->left->val = val;
} else if(val > root->val){ // branch to right of tree if new value is greater than root value
if(root->right == NULL){
root->right = malloc(sizeof(struct node));
}
root->right->val = val;
}
}
어떤 이유로 든 삽입에 문제가 없습니다. 나는 5와 3을 모두 입력 할 수있다. 하지만 root -> val에 있어야하는 '5'값을 출력 할 수 없습니까? 프로그램이 완전히 충돌합니다. 나는 뭔가를 간과 했는가?
첫 번째'insert()'다음에'root'의 포인터 값을 출력 해보십시오 - 여러분이 생각하는 것과 다릅니다 ... – John3136
나는 멍청한 것처럼 보입니다. – Sato
당신이 한 가지 방법은 연구를하지 않고 있었다. 그래서 링크 된 목록/나무 게시물의 절반 정도가이 '업데이트 만 로컬 바'문제가 있습니다. – ThingyWotsit