Trees
Trees
Searching
Searching
• Sequential Searches
• Time is proportional to n
• We call this time complexity O(n)
• Pronounce this “big oh” of n
• Both arrays (unsorted) and linked lists
• Binary search
• Sorted array
• Time proportional to log2 n
• Time complexity O(log n)
Searching - Binary search
• Creating the sorted array
• AddToCollection
• adds each item in correct place
• Find position c1 log2 n
• Shuffle down c2 n
• Overall c1 log2 n + c2 n
Dominant
or c2 n term
• Each add to the sorted array is O(n)
? Can we maintain a sorted array
with cheaper insertions?
Trees
• Binary Tree
• Consists of
• Node
• Left and Right sub-trees
• Both sub-trees are binary trees
Trees
• Binary Tree
• Consists of
• Node
• Left and Right sub-trees Note the
• Both sub-trees are binary trees recursive
definition!
Each sub-tree
is itself
a binary tree
Trees - Implementation
• Data structure
struct t_node {
void *item;
struct t_node *left;
struct t_node *right;
};
struct t_collection {
Node root;
……
};
Trees - Implementation
• Find
extern int KeyCmp( void *a, void *b );
/* Returns -1, 0, 1 for a < b, a == b, a > b */
n = c->root;
FindInTree( n, &key );
FindInTree(n->right,&key );
FindInTree(n->left,&key );
return n->item;
Trees - Performance
• Find
• Complete Tree
• Height, h
• Nodes traversed in a path from the root to a leaf
• Number of nodes, h
• n = 1 + 21 + 22 + … + 2h = 2h+1 - 1
• h = floor( log2 n )
Trees - Performance
• Find
• Complete Tree
• ??
Trees - Addition
• Take this list of characters and form a tree
A B C D E F
• In this case
? Find
? Add
? Delete