Search Sorted Array: Binary Search Linked List: Linear Search Can we Apply the Binary Search algorithm on a linked list? Why not? O(log N) O(N)
Sorted Array Rigid Structure Search: O (log n) Fixed Size Need to know the size of the largest data set Wastage Search: O (log n) Insertion: O (n) - data movement Deletion: O (n) - data movement
Binary Search Tree Binary Tree Dynamic Structure (size is flexible) Data is stored in a sorted fashion A special class of BST has the following properties: Search: O (log n) Insertion: O (log n) Deletion: O (log n)
Binary Search Tree (BST) A BST is a binary tree with the following properties: Data value in the root node is greater than all the data values stored in the left subtree and is less than or equal to all the values stored in the right subtree. Both the left subtree and right subtree are BSTs.
15 20 10 2 12 18 25 28 14 11 23
23 30 18 10 20 27 32 50 15 6
Violating the condition for BST 23 30 18 10 20 27 32 50 19 6 Violating the condition for BST
search(12) 15 20 10 2 12 18 25 28 14 11 23 15 10 12 t
search(23) 15 20 10 2 12 18 25 28 14 11 23 15 20 25 23 t
Binary Search Tree Search TreeNode * BinaryTree::search(int key) { TreeNode *t = root; while (t != NULL) { if (t->data == key) break; else if (t->data > key) t = t->left; else t = t->right; } return t;
search(13) 15 20 10 2 12 18 25 28 14 11 23 15 10 12 14 Æ t
insert(4) insert(19) insert(13) 15 20 10 2 12 18 25 28 14 11 23
Binary Search Tree Search Parent void BinaryTree::searchParent(int key, TreeNode*& current, TreeNode*& previous) { current = root; previous = NULL; while (current != NULL && current -> data != key) { previous = current; if (current->data > key) current = current->left; else current = current->right; }
Binary Search Tree – Insert void BinaryTree::insert(int key) { TreeNode *newTreeNode, *current, *previous; newTreeNode = new TreeNode; newTreeNode ->left = NULL; newTreeNode ->right = NULL; newTreeNode->data = key; if (!root) root = newTreeNode; else { findParent(key, current, previous); if (current == NULL) { if (previous->data > key) previous->left = newTreeNode; else previous->right = newTreeNode; } delete newTreeNode;
insert(13) 15 20 10 2 12 18 25 28 14 11 23 15 10 12 14 13 Æ Æ
delete(2) delete(14) delete(12) 15 20 10 2 12 18 25 28 14 11 23 13
Delete a node from a BST Locate the desired node by search; call it t If t is a leaf, disconnect it from its parent and set the pointer in the parent node equal to NULL If it has only one child then remove t from the tree by making t’s parent point to its child. Otherwise, find the largest/smallest among t’s LST/RST; call it p. Copy p’s information into t. Delete p.
Time Complexity 15 20 10 2 12 18 25 28 14 11 23 Search Insert Delete
O(k) where k is the height 15 insert(15) 18 insert(18) insert(20) 20 insert(26) 26 insert(27) insert(34) 27 34 Time Complexity O(k) where k is the height
Height Balanced Trees k = log (n)