Understanding Binary Search Trees: Insertion, Deletion, and Key Operations
60 likes | 182 Views
Explore the essential operations of Binary Search Trees (BSTs) including searching, insertion, deletion, and finding minimum/maximum values. BST properties ensure that every node's left subtree contains lesser keys while the right subtree holds greater keys. Learn the procedures for in-order tree traversal, searching for keys, tree insertion, and deletion of nodes based on their child configurations. Master these concepts for effective data organization and retrieval in computer science.
Understanding Binary Search Trees: Insertion, Deletion, and Key Operations
E N D
Presentation Transcript
Binary Search Trees (13.1/12.1) • Support Search, Minimum, Maximum, Predecessor, Successor, Insert, Delete • In addition to keyeach node has • left = left child, right = right child, p = parent • Binary search tree property: • all keys in the left subtree of x key[x] • all keys in the right subtree of x key[x] • Resembles quicksort
In-Order-Tree Walk • Procedure In-Order-Tree(x) (O(n)) • In-Order-Tree(left[x]) • print key[x] • In-Order-Tree(right[x]) 7 5 8 3 6 9 2 4 6
Searching (13.2/12.2) Searching (O(h)): Given pointer to the root and key Find pointer to a nod with key or nil Procedure Tree-Search(x,k) if k = key[x], then return x if k < key[x] then return Tree-Search(left[x]) else return Tree-Search(right[x]) IterativeTree-Search(x,k) while k key[x] do if k < key[x] then x left[x] else x right[x] return x 7 5 8 3 6 9 2 4 6
Min-Max, Successor-Predecessor • MIN: go to the left x left[x] • MAX: go to the right x right[x] • Procedure Tree-Successor(x) • if right[x] nil then return MIN(right[x]) • y = p[x] • while y nil and x = right[y] • x y • y p[y] • return y 7 5 8 3 6 9 2 4 6
Insertion (13.3/12.3) O(h) operation 7 5 8 3 6 9 2 4 6
7 7 5 8 5 9 3 6 9 3 6 2 4 6 2 4 6 Deletion (13.3/12.3) • Tree-Delete (T, z): • z has no children, has 1 child, • has two children: then its successor has only child (which?) 7 7 7 5 8 5 8 5 8 2 6 9 3 6 9 3 6 9 1 3 6 1 6 1 4 6 4 4