Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Search Trees (13.1/12.1)

Similar presentations


Presentation on theme: "Binary Search Trees (13.1/12.1)"— Presentation transcript:

1 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] all keys in the right subtree of x  key[x] Resembles quicksort

2 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

3 Searching (13.2/12.2) Searching (O(h)): Procedure Tree-Search(x,k)
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]) Iterative Tree-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

4 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

5 Insertion (13.3/12.3) O(h) operation 7 5 8 3 6 9 2 4 6

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 5 6 3 2 8 9 4 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


Download ppt "Binary Search Trees (13.1/12.1)"

Similar presentations


Ads by Google