Here's some code in C. Basically, It create a small binary tree and then traverse it in pre-order recursively. While I expect '1 2 3', it keeps give me 'printf' result '0 0 3'.
Does anybody have any idea about the code below?
#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;
}