Upload
leo-fox
View
25
Download
0
Embed Size (px)
DESCRIPTION
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). - PowerPoint PPT Presentation
Citation preview
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)
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
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
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24 26
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24 26 31
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24 26 31 34
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24 26 31 34 37
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24 26 31 34 37 42
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24 26 31 34 37 42 48
Traversing a Tree
26
34 42
517
37
24
48
31
18
Start with the root.
Traverse Left SubtreePrint Node ValueTraverse Right Subtree
7 18 24 26 31 34 37 42 48 51