I am learning C and found a basic tree implementation in my C book:
#include <stdio.h>
#include <stdlib.h>
struct tree_node {
int data;
struct tree_node *left_p, *right_p;
};
struct tree_node *t_search(struct tree_node *root, int v) {
while (root) {
printf("Looking for %d, looking at %d\n", v, root->data);
if (root->data == v)
return root;
if (root->data > v)
root = root->left_p;
else
root = root->right_p;
}
return 0;
}
int t_insert(struct tree_node **root, int v) {
while (*root) {
if ((*root)->data == v)
return 1;
if ((*root)->data > v)
root = &((*root)->left_p);
else
root = &((*root)->right_p);
}
if ((*root = (struct tree_node *) malloc(sizeof(struct tree_node))) == 0)
return 2;
(*root)->data = v;
(*root)->left_p = 0;
(*root)->right_p = 0;
return 0;
}
int main(void) {
struct tree_node *tp, *root_p = 0;
int i;
t_insert(&root_p, 4);
t_insert(&root_p, 2);
t_insert(&root_p, 6);
t_insert(&root_p, 1);
t_insert(&root_p, 3);
t_insert(&root_p, 4);
t_insert(&root_p, 7);
for (i = 0; i < 9; i++) {
tp = t_search(root_p, i);
if (tp)
printf("%d found\n", i);
else
printf("%d not found\n", i);
}
return 0;
}
While the code seems to be straight forward, I am having a hard time to understand the t_insert function. Why does it take in a struct tree_node **root instead of struct tree_node *root? t_serach is virtually the same code but uses only a pointer and not a pointer pointer. Maybe another example would explain the issue in a better way.
For what it's worth: I am from a Java background.
Note: Yes, I know the tree is not rebalanced upon insertion.
t_insertmodifies variableroot(set it to just inserted value). But it also have an error: instead of setting to zero pointers to neighbours of newly inserted "leaf" you should set them to point to left and right "leafs". Also you must check return value: 2 signals an error (you must signal that there's maybe not enough memory).root = &((*root)->left_p);. It will be sufficient to just writeroot = &(*root)->left_p;The author of the book should know this.&(*root)->left_p.->and[]bind tighter than anything else, and that=and,are weaker than anything else. It may take a few monthts, but it will increase the readability in the end. Matching operator precedence is easier for the human eye+mind than matching parentheses.