Download presentation
Presentation is loading. Please wait.
1
12.Binary Search Trees Hsu, Lih-Hsing
2
Computer Theory Lab. Chapter 12P.2 12.1 What is a binary search tree? Binary-search property: Let x be a node in a binary search tree. If y is a node in the left subtree of x, then key[y] key[x]. If y is a node in the right subtree of x, then key[x] key[y].
3
Computer Theory Lab. Chapter 12P.3 Binary search Tree
4
Computer Theory Lab. Chapter 12P.4 Inorder tree walk INORDER_TREE_WALK(x) 1if 2then INORDER_TREE_WALK(left[x]) 3print key[x] 4INORDER_TREE_WALK(right[x])
5
Computer Theory Lab. Chapter 12P.5 Theorem 12.1 If x is the root of an n-node subtree, then the call INORDER-TREE-WALK(x) takes (n) time.
6
Computer Theory Lab. Chapter 12P.6 Preorder tree walk Postorder tree walk
7
Computer Theory Lab. Chapter 12P.7 12.2 Querying a binary search tree
8
Computer Theory Lab. Chapter 12P.8 TREE_SEARCH(x,k) 1if or 2then return x 3if 4then return TREE_SEARCH(left[x],k) 5else return TREE_SEARCH(right[x],k)
9
Computer Theory Lab. Chapter 12P.9 ITERATIVE_SEARCH(x,k) 1While or 2do if 3then 4then 5return x
10
Computer Theory Lab. Chapter 12P.10 MAXIMUM and MINIMUM TREE_MINIMUM(x) 1 while left[x] NIL 2 do x left[x] 3 return x TREE_MAXIMUM(x) 1 while right[x] NIL 2 do x right[x] 3 return x
11
SUCCESSOR and PREDECESSOR
12
Computer Theory Lab. Chapter 12P.12 TREE_SUCCESSOR 1 if 2 then return TREE_MINIMUM(right[x]) 3 4 while and 5 do 6 7 return y
13
Computer Theory Lab. Chapter 12P.13 Theorem 12.2 The dynamic-set operations, SEARCH, MINIMUM, MAXIMUM, SUCCESSOR, and PREDECESSOR can be made to run in O(h) time on a binary search tree of height h.
14
12.3 Insertion and deletion
15
Computer Theory Lab. Chapter 12P.15 Tree-Insert(T,z) 1 y NIL 2 x root[T] 3 while x NIL 4 do y x 5if key[z] < key[x] 6 then x left[x] 7 else x right[x] 8 p[z] y Insertion
16
Computer Theory Lab. Chapter 12P.16 9 if y = NIL 10 then root[T] z tree T was empty 11 else if key[z] < key[y] 12 then left[y] z 13else right[y] z
17
Computer Theory Lab. Chapter 12P.17 Inserting an item with key 13 into a binary search tree
18
Computer Theory Lab. Chapter 12P.18 Tree-Delete(T,z) 1 if left[z] = NIL or right[z] = NIL 2 then y z 3 else y Tree-Successor(z) 4 if left[y] NIL 5then x left[y] 6else x right[y] 7 if x NIL 8 then p[x] p[y] Deletion
19
Computer Theory Lab. Chapter 12P.19 9 if p[y] = NIL 10 then root[T] x 11else if y = left[p[y]] 12then left[p[y]] x 13else right[p[y]] x 14 if y z 15then key[z] key[y] 16 copy y’s satellite data into z 17 return y
20
Computer Theory Lab. Chapter 12P.20 z has no children
21
Computer Theory Lab. Chapter 12P.21 z has only one child
22
Computer Theory Lab. Chapter 12P.22 z has two children
23
Computer Theory Lab. Chapter 12P.23 Theorem 12.3 The dynamic-set operations, INSERT and DELETE can be made to run in O(h) time on a binary search tree of height h.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.