Binary Search
Binary Search
Presented By
Halima Binta Rashid
Binary Search Tree
Root
2
All < Root Root<= All
Cont.
Following is a pictorial representation of BST
We observe that the root node key (27) has all less-valued
keys on the left sub-tree and the higher valued keys on the
right sub-tree. 3
2 8
2
8
1 4 1 4
7 4
3
3
1
8
2.5
4
2.4
7 5
6
BST Searching
Suppose T is a binary search tree.
Suppose an ITEM of information is given. The following
algorithm finds the location of ITEM in the binary search tree
T, or inserts ITEM as a new node in its appropriate place in
the tree.
(a). Compare ITEM with the root node N of the tree
(I). If ITEM < N, proceed to the left child of N.
(II). If ITEM > N, proceed to the right child of N.
(b). Repeat Step (a) until one of the following occurs:
(I). We meet a node N such that ITEM = N. In this case the search is
successful.
(II). We meet an empty subtree, which indicates that the search is 6
7
Cont.
38 38
14 56 14 56
45 82 45 82
8 23 8 23
70 70
18 18
20
9
Cont.
10
Successor and Predecessor
The Successor of a node X is the node with the smallest key
greater than X.
The Predecessor of a node X is the node with the largest key
smaller than X.
11
Deleting in a Binary Search Tree
Suppose T is a Binary search tree, and suppose an ITEM of
information is given.
Case-1: N has no children. Then N is deleted from T by
simply replacing the location of N in the parent node P(N)
by the null pointer.
Case-2: N has exactly one child. Then N is deleted from T
by simply replacing the location of N in the parent node
P(N) by the location of the only child of N.
Case-3: N has two children. Let S(N) denote the inorder
successor of N. ( The reader can verify that S(N) does not
have a left child.) Then N is deleted from T by first deleting
S(N) from T (by using Case-1 or Case-2) and then replacing 12
node N in T by the node S(N).
Deleting in a Binary Search Tree
Suppose T is a Binary search tree, and suppose an ITEM of
information is given.
Case-1: N has no children. Then N is deleted from T by
simply replacing the location of N in the parent node P(N)
by the null pointer.
Example-1: Delete key=7 Example-2: Delete key=35
13
Cont.
Case-2: N has exactly one child. Then N is deleted from T by
simply replacing the location of N in the parent node P(N) by
the location of the only child of N.
14
Cont.
Case-3: N has two children. Let S(N) denote the inorder
successor of N.Then N is deleted from T by first deleting
S(N) from T and then replacing node N in T by the node
S(N).
15
Cont.
Replace with the largest key in the left subtree or the smallest
in the right subtree.
Example-1: Delete key=10
16
Cont.
Which node is the largest key in the left subtree?
17
18