7 BST
7 BST
25 77>70 25 97>70
70 70
90 77<90 90 97>90
10 38 10 38
13 77 99 13 77 99 97<90
77=77
null
How much time will it take?
What would be the worst case scenario?
Grey node is shown here to present null
node, just for understanding
Start
1. If node== null OR key==node.key // value found or not found
2. Return node
3. Else If key < node.key // < node.key
4. Return BST_SEARCH( node.left, key)
5. Else // > node.key
6. Return BST_SEARCH( node.right, key)
End
5 Saba Anwar, Computer Science Department- CIIT Lahore 21/03/2025
Insertion
Let say we want to insert 5
What is the correct position for it
5<10 5<50 50
Move to left
Left child of 10 is null 5<25 25 70
Make 5 it’s left child
5<10 10 38 90
13 77 99
null
5<25 25 25
70 70
5<10 10 38 90 10 38 90
13 77 99 5 13 77 99
null
50 85>50 50
25 70 85>70 25 70
10 38 90 85<90 10 38 90
85>77
5 13 77 99 5 13 77 99
85
null
5 13 77 99
85
85
25 70 25 70
10 38 90 10 38 90
5 13 77 99 5 13 77 99
85
null
25 70 25
10 38 90 10 38 90
5 13 77 99 5 13 77 99
85 85
85
50 50
50
25 70 38 70 38 70
10 38 90 10 38 90
10 90
5 13 77 99 5 13 77 99 5 13 77 99
85 85
85
30 36
36 39
While(curr.left!=null)
25 70
curr=curr.left
End While
10 38 90
Return curr
5 13 77 99
30 36
36 39
50 65 So rather than
jumping to successor
node, start from
25 70 25 most immediate
right node, and
10 38 65 90 10 38 systematically delete
successor node
5 13 77 99 5 13
85
Reason: when function is called with successor as root, it store child of successor to right of current node,
which in this case is null, and sub-tree starting at 70 is removed
24 Saba Anwar, Computer Science Department- CIIT Lahore 21/03/2025
Deletion
Case 3: If Node has two child
Even though it does not affect BST property if you choose successor or predecessor,
but it is good to choose randomly between them to maintain tree balance
Otherwise.
Tree will become skewed. One side will become extremely short than other
10 38 90
5 13 77 99
85