Sunteți pe pagina 1din 45

Data Structures (CS 210)

BINARY SEARCH TREE

Asma Sattar
asma.sattar@nu.edu.pk
Topics

• Introduction of BST
• Insertion in BST
• Search in BST
• Deletion in BST
• Finding smallest element in BST
• Find Largest Element in BST

Datastructures and Algorithms 2


Binary Search Tree
• A BST is a binary tree where nodes are ordered in the following way:
• each node contains one key (also known as data)
• the keys in the left subtree are less then the key in its parent node,
in short L < P;
• the keys in the right subtree are greater the key in its parent node,
in short P < R;
• duplicate keys are not allowed.

• The basic idea behind this data structure is to have such a storing
repository that provides the efficient way of data sorting, searching
and retrieving.
Binary Search Tree
• For every node, X, in the tree,
• the values of all the keys in its left subtree are smaller than the key value of X,
• the values of all the keys in its right subtree are larger than the key value of X.

• Example
• X>Y
• X<Z

Y Z
Binary Search Tree Examples (on board)
13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18

Traversal:
Ascending Order??
Descending Order
Binary Search Trees Examples
• Examples

5
10 10
2 45
5 30 5 45
30
2 25 45 2 25 30
10

25
Binary Not a binary
search trees search tree
Binary Search Tree Operations
There are many operations one can perform on a binary search tree.

a) Creating a binary search tree


b) Finding a node in a binary search tree
c) Inserting a node into a binary search tree
d) Deleting a node in a binary search tree.
e) Traversing a binary search tree.

We will briefly cover all of these operations with their general algorithms
Iimplementation and examples.
Creating a Binary (Search) Tree

• We will use a simple class that implements a binary tree to store


integer values.

• We create a class called IntBinaryTree.


Basic Structure of Binary Search Tree
• The basic node of our binary tree has the following struct declaration
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
}
• The class IntBinaryTree declaration is –
class IntBinaryTree
{
private:
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
};
TreeNode *root;
Basic Structure of Binary Search Tree

void destroySubTree(TreeNode *);


void deleteNode(int, TreeNode *);
void displayInOrder(TreeNode *);
void displayPreOrder(TreeNode *);
void displayPostOrder(TreeNode *);
public:
IntBinaryTree() { root = NULL; } // constructor
~IntBinaryTree() { destroySubTree(root); } // Destructor
void insertNode(int);
bool searchNode(int);
void remove(int);
void showNodesInOrder(void) {displayInOrder(root); }
void showNodesPreOrder() {displayPreOrder(root); }
void showNodesPostOrder() {displayPostOrder(root); }
};
Basic Structure of Binary Search Tree
The root pointer is the pointer to the binary tree. This is similar
to the head pointer in a linked list.

The root pointer will point to the first node in the tree, or to NULL
(if the tree is empty).

It is initialized in the constructor.

The destructor calls destroySubTree, a private member function,


that recursively deletes all the nodes in the tree.
Finding a node in a binary search tree
• Recall that a BST has the following key property :
• Smaller values in left subtree
• Larger values in right subtree

• For searching for a node, make use of this property


Example Binary Searches
• Find ( root, 2 )

root
10 5
10 > 2, left 5 > 2, left
5 30 5 > 2, left 2 45 2 = 2, found
2 = 2, found
2 25 45 30

10

25
Example Binary Searches
• Find (root, 25 )

10 5
10 < 25, right 5 < 25, right
5 30 30 > 25, left 2 45 45 > 25, left
25 = 25, found 30 > 25, left
2 25 45 30
10 < 25, right
10 25 = 25, found

25
Recursive Search of Binary Tree

Node *Find( Node *n, int key) {


if (n == NULL) // Not found
return( n );
else if (n->data == key) // Found it
return( n );
else if (n->data > key) // In left subtree
return Find( n->left, key );
else // In right subtree
return Find( n->right, key );
}
Node * n = Find( root, 5);
Searching the Tree
The IntBinaryTree class has a public member function called searchNode, that
returns true if a value is found in the tree, or false otherwise.
The function starts at the root node, and traverses the tree, until it
finds the search value, or runs out of nodes.
bool IntBinaryTree::searchNode(int num)
{
TreeNode *nodePtr = root;
while (nodePtr!=NULL)
{
if (nodePtr->value == num)
return true;
else if (num < nodePtr->value)
nodePtr = nodePtr->left;
else
nodePtr = nodePtr->right;}
return false;
}
Program
// This program builds a binary tree with 5 nodes.
// The SearchNode function determines if the
// value 3 is in the tree.
#include <iostream.h>
#include "IntBinaryTree.h"
void main(void)
{
IntBinaryTree tree;
cout << "Inserting nodes.\n";
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
if (tree.searchNode(3))
cout << "3 is found in the tree.\n";
else
cout << "3 was not found in the tree.\n";
}
Output
Inserting nodes.
3 is found in the tree.
Inserting a node into a binary search tree

• The code to insert a new value in the tree is fairly straightforward.

• First, a new node is allocated, and its value member is initialized with
the new value.
Binary Search Tree – Insertion
• Algorithm
1. Perform search for value X
2. Search will end at node Y (if X not in tree)
3. If X < Y, insert new leaf X as new left subtree for Y
4. If X > Y, insert new leaf X as new right subtree for Y
• Observations
• Insertions may unbalance tree
Example Insertion

• Insert ( 20 )
10 10 < 20, right
30 > 20, left
5 30
25 > 20, left
2 25 45 Insert 20 on left

20
Insertion

Note, we assume that our binary tree will store no duplicate values.
void IntBinaryTree::insertNode(int num)
{
TreeNode *newNode,// Pointer to a new node
*nodePtr;// Pointer to traverse the tree
// Create a new node
newNode = new TreeNode;
newNode->value = num;
newNode->left = newNode->right = NULL;

if (!root)// Is the tree empty?


root = newNode;

else{
nodePtr = root;
Insertion
while (nodePtr != NULL)
{
if (num < nodePtr->value){
if (nodePtr->left!=Null)
nodePtr = nodePtr->left;
else{
nodePtr->left = newNode;
Break;}
}
else if (num > nodePtr->value){
if (nodePtr->right !=Null)
nodePtr = nodePtr->right;
else{
nodePtr->right = newNode;
Break;}
}
else{
cout << "Duplicate value found in tree.\n";
Break;}
}
}
}
Program

// This program builds a binary tree with 5 nodes.


#include <iostream.h>
#include "IntBinaryTree.h"
void main(void)
{
IntBinaryTree tree;
cout << "Inserting nodes. ";
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
cout << "Done.\n";
}
Shape of the BST
Figure shows the structure of the binary tree built by the
program.
Note: The shape of
the tree is determined
by the order in which
the values are
inserted. The root
node in the diagram
above holds the value
5 because that was
the first value inserted.
Task
Insert 15, 25, 40, 3, 7, 1, 14, 5, 6
Search 6 : which nodes are visited
Removing a Node

• Leaf node

• Desired node has one child

• Desired node has two children


BST Operations: Removal

 removes a specified item from the BST and adjusts the tree
 uses a binary search to locate the target item:
 starting at the root it probes down the tree till it finds the
target or reaches a leaf node (target not in the tree)
removal of a node must not leave a ‘gap’ in the tree,
Removal in BST - Pseudocode
method remove (key)
I if the tree is empty return false
II Attempt to locate the node containing the target using the binary search
algorithm
if the target is not found return false
else the target is found, so remove its node:

Case 1: if the node has 2 empty subtrees


replace the link in the parent with null
Case 2: if the node has no left child
- link the parent of the node
- to the right (non-empty) subtree

if the node has no right child


- link the parent of the target
- to the left (non-empty) subtree
Removal in BST - Pseudo code

Case 3:
if the node has a left and a right subtree
- replace the node's value with the max value in the left subtree=Pred
- delete the max node in the left subtree
Removal in BST: Example

Case 1: removing a node with 2 EMPTY SUBTREES

parent
7

5 9
Del node

4 6 8 10

7
Removing 4
replace the link in the parent
with null 5 9

6 8 10
Removal in BST: Example

Case 2: removing a node with 1 EMPTY SUBTREE

the node has no left child:


link the parent of the node to the right (non-empty) subtree

parent
parent

7 7
Del node

5 9 cursor 5 9

6 8 10 6 8 10
Removal in BST: Example
Case 2 : removing a node with 1 EMPTY SUBTREE

the node has no right child:


link the parent of the node to the left (non-empty) subtree

Removing 5
parent
parent

7 7
Del node

5 9 5 9

4 8 10 4 8 10
Removal in BST: Example

Case 3: removing a node with 2 SUBTREES


- replace the node's value with the max value in the left subtree
- delete the max node in the left subtree
What other element
can be used as
Removing 7
replacement?

Del node

7 6

5 9 5 9

4 6 8 10 4 8 10
36
Pseudocode
DeleteKey(x, node *root)

Save =null // parent of the node you want to delete


Curr = root // node you want to delete

While (curr!=Null)
If (curr-> key==x)
break the loop
Else if (x > curr-> key)
save=curr
curr= curr-> right
Else if (x < curr-> key)
save=curr
curr= curr-> left
If (curr->data == key)
{
Case :1
If (curr->left== Null && curr->right== Null)
{ if (curr==root)
root=Null
if (save->left=current)
save->left=Null
if (save->right=current)
save->right=Null
delete current ;
}

Datastructures and Algorithms 38


Case 2:
if (curr->left!=Null && curr->right==Null)
{ if curr==root
root= curr->left; delete current
else
save->left= curr->left
delete curr }

Datastructures and Algorithms 39


if (curr->right!=Null && cuur->left==Null)
{ if curr==root
root= curr->right; delete current
else
save->right= curr->right
delete curr }

Datastructures and Algorithms 40


Case 3:
If (curr->left !=Null & curr-> right!=Null)
{PredParent=cur // parent of pred
pred= curr->left
While (pred->right!=null)
{ PredParent=pred;
pred=pred->right
}
swap (pred-> key , curr-> key)
if (pred->left==null && pred->right==null)
{ if (PredParent->left=Pred) PredParent->left=Null
if (PredParent->right=Pred) PredParent->right=Null
}
else
PredParent->right=pred->left
delete pred
}
Datastructures and Algorithms 41
Task

• Delete 7
• Delete 3
• Delete 8
• Delete 14

Datastructures and Algorithms 42


Smallest node in BST
int minValue(struct node* node) {
struct node* current = node;

/* loop down to find the leftmost leaf */


while (current->left != NULL) {
current = current->left;
}
return(current->data);
}
Largest Node in BST

int maxValue(struct node* node) {


struct node* current = node;

/* loop down to find the leftmost leaf */


while (current->right != NULL) {
current = current->right;
}
return(current->data);
}
Applications of BST

1. the most common application is to efficiently store data in sorted


form in order to access and search stored elements quickly. Map,
set
2. Expression trees
• Leaves represents operands, operators are at non-leaf nodes
• Each traversal order yields respective expression

Source: Allen Weiss


References

• Nell Dale Chapter#8


• Schaum’s Outlines Chapter#7
• D. S. Malik Chapter#11
• http://www.thegeekstuff.com/2013/02/c-binary-tree/

S-ar putea să vă placă și