Trees
What is a tree? You know… tall green leafy possibly fruit branches roots I’m sure you’ve seen them
In the context of C (and CS in general) Trees are a Data Structure (Like a linked list) They Are upside-down Have one root Have branches Have leaves (No fruit)
A Tree (In general)
Nodes
Edges (Links (Pointers))
The Root
Leaves
Branches (A.K.A. Sub-Trees)
Parent / Children
Some info The root has no parent The leaves have no children The interior nodes have at least one child, and a parent
Types of trees Binary trees Every node has (at most) two childen Trinary trees Every node has (at most) three childen N-ary trees Every node has as many children as it wants/needs
We care about binary trees
Binary search trees
Binary Trees typedef struct S_tree { int value; // For example struct S_tree *left, *right; } tree; Just like a linked list, but instead of one pointer, it has two! (left and right)
In Order Traversal Printing an entire binary search tree. void print_tree(tree *t) { if (t == NULL) return; print_tree(t->left); printf(“%d\n”,t->val); print_tree(t->right); } Recursion!
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree 7
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree 7 18
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree
Traversing a Tree Start with the root. Traverse Left Subtree Print Node Value Traverse Right Subtree