60 likes | 165 Views
Binary Search Trees (13.1/12.1). Support Search, Minimum, Maximum, Predecessor, Successor, Insert, Delete In addition to key each node has left = left child, right = right child, p = parent Binary search tree property: all keys in the left subtree of x key[x]
E N D
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