Binary Search Trees
Binary Search Trees
Binary Search Trees
• Similarly, if it is greater than the root, search the right subtree. This
process is repeated until the value is found or the indicated subtree is null.
• If the searched value is not found before a null subtree is reached, then the
item must not be present in the tree.
Searching a BST
To search for an element with key x:
Begin at root
If root is nil then
search tree has no elements and search is
unsuccessful
Else compare x with key in root
If X equals search key then
search terminates successfully
If x less than key in root, then
search left subtree
Else if x greater than key in root then
search right subtree.
Programming logic
if (T == NULL) return NULL;
else
if ( X < T->element ) return find(
X, T->left );
else
if ( X > T->element ) return find(
X, T->right );
else
return T;
Recursion VS iteration
• Iteration means the act of repeating a process usually with
the aim of approaching a desired goal or target or result.
Each repetition of the process is also called an "iteration",
and the results of one iteration are used as the starting
point for the next iteration.
• Recursion is method where the solution to a problem
depends on solutions to smaller instances of the same
problem
Recursion VS iteration
• Computing the recurrence relation for n = 4:
• b4
• =4 * b3
= 4 * 3 * b2
• = 4 * 3 * 2 * b1
• = 4 * 3 * 2 * 1 * b0
• =4*3*2*1*1
• =4*3*2*1
• =4*3*2
• =4*6
• = 24
• Iteration:
• var i, a := 0
• for i from 1 to 3
• {
• a := a + I
• }
• print a
Insertion into a BST
•Insertion begins as a search would begin; if the root is not
equal to the value, we search the left or right subtrees as
before.
•Eventually, we will reach an external node and add the
value as its right or left child, depending on the node's
value.
•In other words, we examine the root and recursively insert
the new node to the left subtree if the new value is less than
the root, or the right subtree if the new value is greater than
or equal to the root.
Insertion into a BST
• To insert new element, key must be unique (unless duplicates are
allowed)
• Search first for the key (i.e., find key)
• If key not found, then insert new element at point where search
terminated
• Example: insert 80,16,25,4,37 into following tree
Recursive Insert Routine
/*2*/ {
/*3*/ if (t == NULL)
/*4*/ {
/*5*/ t = new TreeNode <Etype> (x);
/*6*/ }
/*7*/ else
/*8*/ if (x < t->element)
/*9*/ Insert(x, t->left);
/*10*/ else
/*11*/ if (x > t->element)
/*12*/ Insert(x, t->right);
/*13*/ //else x is in tree already. Do nothing.
/*14*/ }
5 30 5 30 2 30
2 25 45 2 25 45 2 25 45
5 30 5 30 5 30
2 25 45 2 25 45 2 45
• Consider the following examples (elements are given in the order they
have been inserted:
List 3: {47,38,25,30,45,8,2,40,120}
findMin/ findMax
• Return the node containing the smallest element in the tree
• Start at the root and go left as long as there is a left child. The
stopping point is the smallest element