I'm implementing a BST in C. If the tree only has 2 leaves and nothing in between, recursion works. But as soon as it goes deeper (eg below 3 levels deep) - the recursion breaks.
My code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node* left;
struct node* right;
} node_t;
void print_tree(node_t* n, int indent) {
//base case, tree leaves
if (n->left == NULL && n->right == NULL) {
printf("%*c", indent, ' ');
printf("%d\n", n->val);
} else {
//print current level
printf("%*c", indent, ' ');
printf("%d\n", n->val);
//then kids
print_tree(n->left, indent+2);
print_tree(n->right, indent+1);
}
}
int bst() {
node_t* n1;
n1 = (node_t*) malloc(sizeof(node_t));
//level 1 children
n1->val = 5;
n1->left = (node_t*) malloc(sizeof(node_t));
n1->right = (node_t*) malloc(sizeof(node_t));
//level 2 children
n1->left->val = 3;
n1->left->left = (node_t*) malloc(sizeof(node_t));
n1->left->right = NULL;
n1->right->val = 10;
n1->right->left = (node_t*) malloc(sizeof(node_t));
n1->right->right = NULL;
//level 3 children
n1->left->left->val = 1;
n1->left->left->left = NULL;
n1->left->left->right = NULL;
n1->right->left->val = 6;
n1->right->left->left = NULL;
n1->right->left->right = NULL;
print_tree(n1, 0);
return 1;
}
What happens:
5
3
1
What I want to happen:
5
3
1
10
6
When I run in debug mode I see that for some reason the base case never triggers and so at some point n itself becomes NULL and the if statement breaks.
Why is the base case not triggering?