CSE 3358 NOTE SET 10 Data Structures and Algorithms
Complexity of Searching a Binary Tree Worst Case: Linked List O(n) Best Case: Complete Binary Tree O(lg n) Average Case: Average Position in Average Tree O(lg n)
Tree Traversal Process of visiting every node exactly one time No implied notion of order, so there are n! different traversals Most are useless because Depth-First Breadth-First
Depth First Searching In – order Left Visit Right Pre – Order Visit Left Right Post – Order Left Right Visit
In - Order template void BST ::inorder(BSTNode *p) { if (p != 0) { inorder (p->left); visit(p); inorder (p->right); } In order Traversal:
Pre - Order template void BST ::preorder(BSTNode *p) { if (p != 0) { visit(p); preorder (p->left); preorder (p->right); } Pre order Traversal:
Post - Order template void BST ::postorder(BSTNode *p) { if (p != 0) { postorder (p->left); postorder (p->right); visit(p); } Post order Traversal:
Breadth-First Traversal Visiting each node top-down-left-to-right Use a queue to store the children of a node when the node is visited Breadth-First Traversal:
Breadth-First Traversal – Implementation Ideas
Breadth-First IMPL template void BST ::breadthFirst(BSTNode *p) { Queue *> queue; BSTNode *p = root; if (p != 0) { queue.enqueue(p); while(!queue.empty()) { p = queue.dequeue(); visit(p); if (p -> left != 0) queue.enqueue(p->left); if (p -> right != 0) queue.enqueue(p->right); }
To Recur or Not to Recur template void BST ::iterativePreorder() { Stack *> travStack; BSTNode *p = root; if (p != 0) { travStack.push(p); while(!travStack.empty()) { p = travStack.pop(); visit(p); if (p->right != 0) travStack.push(p->right); if (p->left != 0) travStack.push(p->left); }
Deleting Three Cases: 1) Node is a leaf Set the pointer from the parent to null. release memory as appropriate. 2) Node has 1 child Set the pointer from the parent to the child of the node to be deleted release memory as appropriate 3) Node has 2 children Will require multi-step process
Deleting: Case Delete 3
Deleting: Case Delete 31
Deleting: Case 3 – Option 1: Deleting by Merging Delete Find the right-most node of the left subtree Make that node the parent of the right subtree (of the node to be deleted)
Deleting: Case 3 – Option 2: Deleting by Copying Delete Find the right-most node of the left subtree Copy the key of that node to the node to be deleted. Delete the node that was copied from.
?