Binary Tree
A binary tree is a node with at most two children, usually named left and right. The empty tree is a null pointer. Every child is itself a binary tree.
Detailed Explanation
The node is a struct with a value and two pointers:
struct Node {
int value;
struct Node *left;
struct Node *right;
};
Nothing in that struct requires the search-tree property. A binary tree can be a heap-shaped complete tree, an expression tree, or an unbalanced mess you built by hand. A BST is a binary tree with an ordering rule. A heap as an array is often not stored as pointers at all.
Walks have names. Preorder visits the node, then left, then right. Inorder visits left, node, right — and on a BST that is sorted order. Postorder visits children first, which is the order you need to free the tree: you cannot free(node) before you free the children if you still need node->left. Level order is BFS with a queue.
Recursion matches the data. void walk(struct Node *n) { if (!n) return; walk(n->left); ... } is short and uses the call stack. A tree of height n — a straight line — uses n frames. For untrusted or degenerate input, walk with an explicit stack.
Ownership is per node. Creating a tree of n values is n allocations if you heap-allocate each node. Destroying it is n frees. A function that returns a subtree pointer must say whether the caller may free it independently of the rest.
Parent pointers are optional. They make "find the successor" easier and make every insert update more fields. Most teaching trees omit them. Graphs that need an upward edge are no longer trees if they also have another path up.
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *left;
struct Node *right;
};
static struct Node *leaf(int value)
{
struct Node *n = malloc(sizeof *n);
if (n == NULL) {
return NULL;
}
n->value = value;
n->left = n->right = NULL;
return n;
}
static void inorder(const struct Node *n)
{
if (n == NULL) {
return;
}
inorder(n->left);
printf("%d ", n->value);
inorder(n->right);
}
static void tree_free(struct Node *n)
{
if (n == NULL) {
return;
}
tree_free(n->left);
tree_free(n->right);
free(n);
}
int main(void)
{
struct Node *root = leaf(2);
if (root == NULL) {
return 1;
}
root->left = leaf(1);
root->right = leaf(3);
inorder(root); /* prints: 1 2 3 */
printf("\n");
tree_free(root);
return 0;
}Common Gotchas
Freeing a node before its children loses those pointers
postorder free, or iterate with an explicit stack.
A linear tree is a list
recursive walks become `O(n)` stack. Bound the height or iterate.
`left` and `right` being `NULL` is the base case
forget the check and you dereference `NULL` at the leaves.
Sharing a subtree between two parents makes `tree_free` a double-free
a tree's children have one parent each.