Web Page - http://www.cs.tau.ac.il/~efif/courses/Software1_Spring_04
while (ptr != NULL) { free(ptr); ptr = ptr->next; } |
typedef struct node { struct node * right; struct node * left; int value; } Node; |
| <=> |
|
node1 = node2; |
Node node = {NULL, NULL, 0}; |
Node *create_node(int value) { Node * tmp = (Node *) malloc(sizeof(Node)); if (!tmp) { fprintf(stderr, "ERROR: not enough memory!\n"); return NULL; } tmp->left = tmp->right = NULL; tmp->value = value; return tmp; } |
void print_tree(Node *root) { if (!root) return; print_tree(root->left); printf("%d ", root->value); print_tree(root->right); } |
Node * insert(Node * root, int value) { Node * parent; Node * child; Node * new_node; new_node = create_node(value); if (!new_node) return NULL; if (!root) return new_node; child = root; while (child) { parent = child; if (child->value > value) child = child->left; else child = child->right; } if (parent->value > value) parent->left = new_node; else parent->right = new_node; return root; } |
typedef void(Op)(void *); |
void traverse_tree(Node * root, Op * op) { if (!root) return; traverse_tree(root->left, op); op((void *)root->value); traverse_tree(root->right, op); } |
void print_node(void * value) { printf("%d ", (int) value); } |
traverse_tree(root, print_node); |