Notes
Outline
Week 7
Binary Search Trees.
Reading  Main:  p479-494
Recall - Binary Search Tree
A Binary Tree such that:
Every node entry has a unique key.
All the keys in the left subtree of a node are less than the key of the node.
All the keys in the right subtree of a node are greater than the key of the node.
Slide 3
Slide 4
Binary Tree Node
Binary Search Tree Node
Binary Search Tree Node
Slide 8
Slide 9
Slide 10
Binary Search Tree
Inorder
Inorder traversal of a Binary Search Tree always gives the sorted order of the keys.
Inorder
Inorder traversal of a Binary Search Tree always gives the sorted order of the keys.
Inorder
Inorder traversal of a Binary Search Tree always gives the sorted order of the keys.
Inorder
Inorder traversal of a Binary Search Tree always gives the sorted order of the keys.
Postorder
Postorder
PREorder
Preorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Inorder
Search
Search
Search: Checklist
if target key is less than current node’s key, search the left sub-tree.
else, if target key is greater than current node’s key, search the right sub-tree.
returns:
if found, or if target key is equal to current node’s key, a pointer to node containing target key.
otherwise, NULL pointer.
Searching Binary Tree
private TreeNode search( TreeNode ptr, TreeData key) {
if ( ptr==null ) return null;
else
if ( ptr.data.equals(key) ) return ptr;
else
if ( key.compareTo(ptr.data) < 0 ) return search( ptr.left, key);
else return search( ptr.right, key);
}
public boolean includes( TreeData key ) {
return (search( root, key ) != null );
}
Retrieving Data from Binary Tree
public TreeData retrieve( TreeData key ); {
TreeNode ptr;
ptr = search( root, key );
if (ptr == null) return null;
else return ptr.data;
}
Search
Search
Search
Search
Search
Search
Search
Search
Search
Insert
Insert
Insert
Create new node for the item.
Find a parent node.
Attach new node as a leaf.
Insert: Recursive
parameters:
pointer to current node (initially: root node).
item to be inserted.
If current node is NULL
Create a new node and return it.
Else if item’s key is less (greater) than current node’s key:
otherwise, let the left (right) child node be the current node, setting the parent left (right) link equal that node, and repeat recursively.
MakeNode
parameter: item to be inserted
steps:
allocate memory for the new node
check if memory allocation is successful
if so, put item into the new node
set left and right branches to NULL
returns: pointer to (i.e. address of) new node
Slide 63
Insert
Insert
Insert
Insert
Insert
Sorting
To sort a sequence of items:
Insert items into a Binary Search Tree.
Then Inorder Traverse the tree.
Sorting: Analysis
Average Case:  O(n log(n))
Sort
Sort
Sort
Sort
Sort
Sort
Sort
Sorting: Analysis