|
|
|
Binary Search Trees. |
|
Reading
Main: p479-494 |
|
|
|
|
|
|
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. |
|
|
|
|
|
|
|
|
|
|
|
|
|
Inorder traversal of a Binary Search Tree always
gives the sorted order of the keys. |
|
|
|
|
Inorder traversal of a Binary Search Tree always
gives the sorted order of the keys. |
|
|
|
|
Inorder traversal of a Binary Search Tree always
gives the sorted order of the keys. |
|
|
|
|
Inorder traversal of a Binary Search Tree always
gives the sorted order of the keys. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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. |
|
|
|
|
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 ); |
|
} |
|
|
|
|
|
|
public TreeData retrieve( TreeData key ); { |
|
TreeNode ptr; |
|
ptr = search( root, key ); |
|
if (ptr == null) return null; |
|
else return ptr.data; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Create new node for the item. |
|
Find a parent node. |
|
Attach new node as a leaf. |
|
|
|
|
|
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. |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
To sort a sequence of items: |
|
Insert items into a Binary Search Tree. |
|
Then Inorder Traverse the tree. |
|
|
|
|
Average Case:
O(n log(n)) |
|
|
|
|
|
|
|
|
|