I picked up some ideas from this website: http://www.cprogramming.com/tutorial/c/lesson18.html
Then I wrote some code to create a binary tree. It is as follows
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int key_value;
struct node *left;
struct node *right;
} node;
void createTree(node * leaf, int depth) {
leaf->key_value = depth;
if (depth == 0) {
leaf->left = 0;
leaf->right = 0;
} else {
leaf->left = (node *) malloc(sizeof(node));
leaf->right = (node *) malloc(sizeof(node));
}
createTree(leaf->left, depth - 1);
createTree(leaf->right, depth - 1);
}
int main() {
node head;
createTree(&head, 3);
(head.left)->key_value = 5;
printf("%d\n", head.left->key_value);
return 0;
}
It compiles just fine but when I run it I get a segmentation fault error. The idea is to start with a node called head, and then give that value 3, then give its two children value 2, etcetera and until we get to depth == 0, at which point we dont make any more leafs.