다음은 C의 코드입니다. 기본적으로 작은 바이너리 트리를 만든 다음 선주문으로 재귀 적으로 트래버스합니다. 나는 '1 2 3'을 기대하지만, 'printf'결과 '0 0 3'을 계속 유지합니다.왜이 C 프로그램을 제대로 실행할 수 없습니까?
누구든지 아래 코드에 대해 어떤 생각을 갖고 있습니까? 내가 생각
#include <stdio.h>
#include <stdlib.h>
typedef struct binary_tree{
struct binary_tree *left;
struct binary_tree *right;
int value;
}binary_tree;
void init_btree(binary_tree *root);
// traverse the tree in pre-order recursively
void pre_order_r(const binary_tree *root){
if(root == NULL){
return;
}
printf("%d ", root->value);
pre_order_r(root->left);
pre_order_r(root->right);
}
int main() {
binary_tree *root = (binary_tree*)malloc(sizeof(binary_tree*));;
init_btree(root);
pre_order_r(root);
printf("\n");
}
void init_btree(binary_tree *root){
root->left = root->right = NULL;
root->value = 1;
binary_tree * p1 = (binary_tree*)malloc(sizeof(binary_tree*));
p1->left = p1->right = NULL;
p1->value = 2;
binary_tree * p2 = (binary_tree*)malloc(sizeof(binary_tree*));
p2->left = p2->right = NULL;
p2->value = 3;
root->left = p1;
root->right = p2;
}
'(binary_tree *) malloc (sizeof (binary_tree *))'->'(binary_tree *) malloc (sizeof (binary_tree)) ' – BLUEPIXY