Sei sulla pagina 1di 115

BINARY TREES

TREES
Introduction
• There are many basic data structures that can be used to solve
application problems.
• Array is a good static data structure that can be accessed randomly and
is fairly easy to implement.
• Linked Lists on the other hand is dynamic and is ideal for application
that requires frequent operations such as add, delete, and update.
• One drawback of linked list is that data access is sequential.
• Then there are other specialized data structures like, stacks and queues
that allows us to solve complicated problems using these restricted
data structures.
• One other data structure is the hash table that allows users to program
applications that require frequent search and updates. They can be
done in O(1) in a hash table.
TREES
Introduction
• Disadvantages of using an array or linked list to store data is the
time necessary to search for an item.
• Since both the arrays and Linked Lists are linear structures the
time required to search a “linear” list is proportional to the size
of the data set.
• For example, if the size of the data set is n, then the number of
comparisons needed to find (or not find) an item may be as bad
as some multiple of n.
• So imagine doing the search on a linked list (or array) with n = 106
nodes.
• Even on a machine that can do million comparisons per second,
searching for m items will take roughly m seconds.
TREES
Introduction
• This not acceptable in today’s world where speed at which we
complete operations is extremely important.
• Time is money.
• Therefore it seems that better (more efficient) data structures are
needed to store and search data.
TREES
Introduction
• The concept of linked data structure (linked list, stack, queue) to
a structure that may have multiple relations among its nodes is
called a tree.
• A tree is a collection of nodes connected by directed (or
undirected) edges.
• A tree is a nonlinear data structure, compared to arrays, linked
lists, stacks and queues which are linear data structures.
A

B C D

E F G H

I J K
TREES
Introduction
• In tree data structure, every individual element is called as Node.
• Node in a tree data structure, stores the actual data of that
particular element and link to next element in hierarchical
structure.
• In a tree data structure, if we have N number of nodes then we
can have a maximum of N-1 number of links.
• Example
INTRODUCTION TO TREES
Advantages of Trees
1. To store information that naturally forms a hierarchy. For
example, the file system on a computer:
2. Trees (with some ordering e.g., BST) provide moderate
access/search (quicker than Linked List and slower than
arrays).
3. Trees provide moderate insertion/deletion (quicker than
Arrays and slower than Unordered Linked Lists).
4. Like Linked Lists and unlike Arrays, Trees don’t have an upper
limit on number of nodes as nodes are linked using pointers.
INTRODUCTION TO TREES
Application of Tree Data Structure
1. Manipulate hierarchical data.
2. Make information easy to search
3. Manipulate sorted lists of data
4. As a workflow for compositing digital images for visual effects
5. Router algorithms
6. Form of a multi-stage decision-making (see business chess).
TERMINOLOGIES
1. Root: 2. Edge:
• In a tree data structure, the first • In a tree data structure, the
node is called as Root Node. connecting link between any
• Every tree must have root node. two nodes is called as EDGE.
We can say that root node is • In a tree with 'N' number of
the origin of tree data structure. nodes there will be a maximum
In any tree, there must be only of 'N-1' number of edges.
one root node.
TERMINOLOGIES
3. Parent: 4. Child:
• In a tree datastructure, the • In a tree data structure, the
node which is predecessor of node which is descendant of
any node is called as PARENT any node is called as CHILD
NODE. Node.
• Parent node can also be defined • In a tree, any parent node can
as "The node which has child / have any number of child
children" nodes.
TERMINOLOGIES
5. Siblings: 6. Leaf:
• In a tree data structure, nodes • In a tree data structure, the
which belong to same Parent node which does not have a
are called as SIBLINGS. child is called as LEAF Node.
• In a tree data structure, the leaf
nodes are also called as
External Nodes / Terminal
node.
TERMINOLOGIES
7. Internal Nodes: 8. Degree:
• In a tree data structure, the • In a tree data structure, the
node which has atleast one total number of children of a
child is called as INTERNAL node is called as DEGREE of
Node. that Node.
• In a tree data structure, nodes • The highest degree of a node
other than leaf nodes are called among all the nodes in a tree is
as Internal Nodes. called as 'Degree of Tree'
• Internal nodes are also called as
'Non-Terminal' nodes.
TERMINOLOGIES
9. Level: 10. Height:
• In a tree data structure, the root • In a tree data structure, the total
node is said to be at Level 0 and number of edges from leaf node
the children of root node are at to a particular node in the
Level 1 and the children of the longest path is called as HEIGHT
nodes which are at Level 1 will be of that Node.
at Level 2 and so on... • In a tree, height of the root node
• In simple words, in a tree each is said to be height of the tree.
step from top to bottom is called • In a tree, height of all leaf nodes
as a Level and the Level count is '0'.
starts with '0' and incremented
by one at each level (Step).
TERMINOLOGIES
11. Depth:
• In a tree data structure, the total number of edges from root node to a
particular node is called as DEPTH of that Node.
• In a tree, the total number of edges from root node to a leaf node in the
longest path is said to be Depth of the tree.
• In simple words, the highest depth of any leaf node in a tree is said to be
depth of that tree.
• In a tree, depth of the root node is '0'.
TERMINOLOGIES
12. Path: 13. Sub Tree:
• In a tree data structure, the • In a tree data structure, each
sequence of Nodes and Edges child from a node forms a
from one node to another node subtree recursively.
is called as PATH between that • Every child node will form a
two Nodes. subtree on its parent node.
• Length of a Path is total
number of nodes in that path.
In below example the path A - B
- E - J has length 4.
TREE REPRESENTATIONS
Introduction
• A tree data structure can be represented in two methods. Those
methods are as follows...
– List Representation
– Left Child - Right Sibling Representation
TREE REPRESENTATIONS
List Representation
• In this representation, we use two types of nodes one for representing
the node with data and another for representing only references.
• We start with a node with data from root node in the tree. Then it is
linked to an internal node through a reference node and is linked to any
other node directly.
• This process repeats for all the nodes in the tree.
TREE REPRESENTATIONS
Left Child - Right Sibling Representation
• In this representation, we use list with one type of node which
consists of three fields namely Data field, Left child reference
field and Right sibling reference field.
• Data field stores the actual value of a node, left reference field
stores the address of the left child and right reference field stores
the address of the right sibling node.
• Graphical representation of that node is as follows...
TREE REPRESENTATIONS
Left Child - Right Sibling Representation
• In this representation, every node's data field stores the actual value of
that node.
• If that node has left child, then left reference field stores the address of
that left child node otherwise that field stores NULL.
• If that node has right sibling then right reference field stores the
address of right sibling node otherwise that field stores NULL.
• The above tree example can be represented using Left Child - Right
Sibling representation as follows...
BINARY TREE
Introduction
• In a normal tree, every node can have any number of children.
• Binary tree is a special type of tree data structure in which every
node can have a maximum of 2 children. One is known as left
child and the other is known as right child.
• A tree in which every node can have a maximum of two children
is called as Binary Tree.
• In a binary tree, every node can have either 0 children or 1 child
or 2 children but not more than 2 children.
BINARY TREE
Introduction
• Non binary trees
Types of BINARY TREE
Strictly binary tree:
• In a binary tree, every node can have a maximum of two children.
• But in strictly binary tree, every node should have exactly two
children or none.
• That means every internal node must have exactly two children.
• A binary tree in which every node has either two or zero number
of children is called Strictly Binary Tree
• Strictly binary tree is also called as Full Binary Tree or Proper
Binary Tree
• A strictly binary tree with n leaves always contains 2n-1 nodes
BINARY TREE
Complete Binary Tree:
• In complete binary tree all the nodes must have exactly two children
and at every level (l) of complete binary tree there must be 2l number
of nodes.
• For example at level 2 there must be 22 = 4 nodes and at level 3 there
must be 23 = 8 nodes.
• A binary tree in which every internal node has exactly two children and
all leaf nodes are at same level is called Complete Binary Tree.
• Complete binary tree is also called as Perfect Binary Tree
BINARY TREE
Left skewed binary tree
• If a binary tree has only left
sub trees, then it is called
left skewed binary tree

Right skewed binary tree


• If a binary tree has only
right sub trees, then it is
called right skewed binary
tree
BINARY TREE
Properties
• If a binary tree contains m nodes at level l, it contains at most 2m
nodes at level l+1
• Binary tree can contain at most 𝟐𝒍 nodes at level l
• A complete binary tree of depth d is the binary tree of depth d
that contains exactly 𝟐𝒍 nodes at each level l between 0 and d.
• Total number of nodes in a complete binary tree of depth d is
given by:
tn = 20 + 21 + 22 + ……………….. + 2𝑑 = σ𝑑𝑗=0 2𝑗 = 2𝑑+1 − 1
• In a complete binary tree, if we know the number of nodes,
depth can calculated using:
𝒅 = log 𝟐 ( 𝒕𝒏 + 𝟏) − 𝟏
BINARY TREE
Node numbering in complete binary Tree
• Number the nodes 1through 2d– 1
• Number by levels from top to bottom.
• Within a level number from left to right.
• Parent of node i is node i / 2, unless i = 1
• Node 1 is the root and has no parent
• Left child of node i is node 2i, unless 2i > n, where n is the
number of nodes. If 2i > n, node i has no left child.
• Right child of node i is node 2i+1, unless 2i+1 > n, where n is the
number of nodes. If 2i+1 > n, node i has no right child.
BINARY TREE REPRESENTATIONS
• A binary tree data structure is represented using two methods.
Those methods are as follows...
– Array Representation
– Linked List Representation
• Consider the following binary tree..
BINARY TREE REPRESENTATIONS
Array Representation
• An array can be used to store the nodes of a binary tree.
• The nodes stored in an array of memory can be accessed
sequentially.
• Suppose a binary tree of depth d. Then at most 2d+1-1nodes can
be there in Tree. (i.e., SIZE = 2d-1)
• Consider a binary tree of depth 2. Then SIZE = 22+1 – 1 = 7. Then
the array A[7] is declared to hold the nodes.
BINARY TREE REPRESENTATIONS
Array Representation
• To perform any operation often we have to identify the parent,
the left child and right child of an arbitrary node.
1. The father of a node having index n can be obtained by (i – 1)/2.
For example to find the father of D, where array index i = 3. Then
the father nodes index can be obtained
= (i – 1)/2
= 3 – 1/2
= 2/2
=1
• i.e., A[1] is the father D, which is B.
BINARY TREE REPRESENTATIONS
Array Representation
2. The left child of a node having index i can be obtained by (2i+1).
– For example to find the left child of C, where array index i = 2. Then
it can be obtained by
= (2i +1)
= 2*2 + 1
=4+1
=5
• i.e., A[5] is the left child of C, which is NULL. So no left child for C.
BINARY TREE REPRESENTATIONS
Array Representation
3. The right child of a node having array index i can be obtained by the
formula (2i + 2).
• For example to find the right child of B, where the array index i = 1.
Then
= (2i + 2)
= 2*1 + 2
=4
• i.e., A[4] is the right child of B, which is E.
BINARY TREE REPRESENTATIONS
Array Representation
4. If the left child is at array index i, then its right brother is at (i +
1). Similarly, if the right child is at index i, then its left brother is
at (i – 1).
• The array representation is more ideal for the complete binary
tree.
• Since there is no left child for node C, i.e., A[5] is vacant.
• Even though memory is allocated for A[5] it is not used, so
wasted unnecessarily.
BINARY TREE REPRESENTATIONS
Array Representation
BINARY TREE REPRESENTATIONS
Linked List Representation
• The most popular and practical way of representing a binary tree
is using linked list (or pointers).
• In linked list, every element is represented as nodes.
• A node consists of three fields such as :
(a) Left Child (LChild)
(b) Information of the Node (Info)
(c) Right Child (RChild)
BINARY TREE
Linked List Representation
• We use double linked list to represent a binary tree.
• In a double linked list, every node consists of three fields. First
field for storing left child address, second for storing actual data
and third for storing right child address.
OPERATIONS ON BINARY TREE
1. Creating an empty Binary tree
2. Traversing a Binary Tree
3. Inserting a new node
4. Deleting a Node
5. Searching for a Node
6. Copying the mirror image of a tree
7. Determine the total no: of Nodes
8. Determine the total no: leaf Nodes
9. Determine the total no: non-leaf Nodes
10. Find the smallest element in a Node
11. Finding the largest element
12. Find the Height of the tree
13. Finding the Father/Left Child/Right Child/Brother of an arbitrary
node
TRAVERSING BINARY TREES RECURSIVELY
Introduction
• Tree traversal is one of the most common operations performed
on tree data structures.
• It is a way in which each node in the tree is visited exactly once in
a systematic manner.
• There are three standard ways of traversing a binary tree. They
are:
1. Pre Order Traversal (root-left-right)
2. In order Traversal (Left-root-right)
3. Post Order Traversal (Left-right-root)
TRAVERSING BINARY TREES RECURSIVELY
Pre Order Traversal (root-left-right)
• In pre-order traversal, the root node is visited (or processed) first,
before traveling through left and right sub trees recursively
• To traverse a non-empty binary tree in pre order following steps
are to be processed
1. Visit the root node
2. Traverse the left sub tree in preorder
3. Traverse the right sub tree in preorder
TRAVERSING BINARY TREES RECURSIVELY
Pre Order Traversal (root-left-right)
• Example:

• A-B-D-I-J-F-C-G-K-H
TRAVERSING BINARY TREES RECURSIVELY
In Order Traversal (left-root-right)
• In In-Order traversal, the root node is visited between left child
and right child.
• In this traversal, the left child node is visited first, then the root
node is visited and later we go for visiting right child node.
• This in-order traversal is applicable for every root node of all
subtrees in the tree.
• This is performed recursively for all nodes in the tree.
• The in order traversal of a non-empty binary tree is defined as
follows :
1. Traverse the left sub tree in order
2. Visit the root node
3. Traverse the right sub tree in order
TRAVERSING BINARY TREES RECURSIVELY
In Order Traversal (left-root-right)
• Example:

• I-D-J-B-F-A-G-K-C-H
TRAVERSING BINARY TREES RECURSIVELY
Post Order Traversal (left-right-root)
• In Post-Order traversal, the root node is visited after left child and
right child.
• In this traversal, left child node is visited first, then its right child
and then its root node.
• This is recursively performed until the right most node is visited.
• The post order traversal of a non-empty binary tree can be
defined as :
1. Traverse the left sub tree in post order
2. Traverse the right sub tree in post order
3. Visit the root node
TRAVERSING BINARY TREES RECURSIVELY
Post Order Traversal (left-right-root)
• Example:

• I-J-D-F-B-K-G-H-C-A
TRAVERSING BINARY TREES RECURSIVELY
Examples:
TRAVERSING BINARY TREES RECURSIVELY
Examples:
BINARY SEARCH TREE
• A binary search tree(BST) is a binary tree. It may be empty. If it is
not empty then it satisfies the following properties:
1. Every element has a key and no two elements have the same key.
2. The keys in the left subtree are smaller than the key in the root.
3. The keys in the right subtree are larger than the key in the root.
4. The left and right subtrees are also binary search trees.

Binary Search Tree Non-Binary Search Tree


BINARY SEARCH TREE
Examples:
• Draw the BST for the keys: 11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31
BINARY SEARCH TREE
Examples:
• Draw the BST for the keys:
13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9,
11, 6, 18
BINARY SEARCH TREE
Pre order Traversal RECURSIVELY
1. Visit the root node
2. Traverse the left sub tree in preorder
3. Traverse the right sub tree in preorder

void preorder (Node * Root)


{
If (Root != NULL)
{
Cout“<<Root → Info;
preorder(Root → Lchild);
preorder(Root → Rchild);
}
}
BINARY SEARCH TREE
IN ORDER TRAVERSAL RECURSIVELY
1. Traverse the left sub tree in order
2. Visit the root node
3. Traverse the right sub tree in order

void inorder (NODE *Root)


{
If (Root != NULL)
{
inorder(Root → Lchild);
cout<<Root → info;
inorder(Root → Rchild);
}
}
BINARY SEARCH TREE
POST ORDER TRAVERSAL RECURSIVELY
1. Traverse the left sub tree in post order
2. Traverse the right sub tree in post order
3. Visit the root node

void postorder (NODE *Root)


{
If (Root != NULL)
{
postorder(Root → Lchild);
postorder(Root → Rchild);
cout<<Root → info;
}
}
BINARY SEARCH TREE OPERATIONS
• The operations performed on binary tree can also be applied to
Binary Search Tree (BST).
• Primitive operators performed on BST :
1. Inserting a node
2. Searching a node
3. Deleting a node
• Another most commonly performed operation on BST is,
traversal.
• The tree traversal algorithm (pre-order, post-order and in-order)
are the standard way of traversing a binary search tree.
BINARY SEARCH TREE OPERATIONS
INSERTING A NODE
• A BST is constructed by the repeated insertion of new nodes to
the tree structure.
• Inserting a node in to a tree is achieved by performing two
separate operations.
1. The tree must be searched to determine where the node is to
be inserted.
2. Then the node is inserted into the tree.
BINARY SEARCH TREE OPERATIONS
INSERTING A NODE
• Suppose a “DATA” is the information to be inserted in a BST.
Step 1: Compare DATA with root node information of the tree
(i) If (DATA < ROOT → Info)
Proceed to the left child of ROOT
(ii) If (DATA > ROOT → Info)
Proceed to the right child of ROOT
Step 2: Repeat the Step 1 until we meet an empty sub tree,
where we can insert the DATA in place of the empty sub
tree by creating a new node.
Step 3: Exit
BINARY SEARCH TREE OPERATIONS
ALGORITHM TO INSERT A NODE
NEWNODE is a pointer variable to hold the
address of the newly created node. DATA is
the information to be pushed.
1. Input the DATA to be pushed and 7. Else If (DATA > ROOT → Info)
ROOT node of the tree. (a) ROOT → RChild = NEWNODE
8. Else
2. NEWNODE = Create a New Node.
(a) Display (“DUPLICATE NODE”)
3. If (ROOT == NULL) (b) EXIT
(a) ROOT=NEW NODE 9. NEW NODE → Info = DATA
4. Else If (DATA < ROOT → Info) 10. NEW NODE → LChild = NULL
(a) ROOT = ROOT → Lchild 11. NEW NODE → RChild = NULL
12. EXIT
(b) GoTo Step 4
5. Else If (DATA > ROOT → Info)
(a) ROOT = ROOT → Rchild
(b) GoTo Step 4
6. If (DATA < ROOT → Info)
(a) ROOT → LChild = NEWNODE
BINARY SEARCH TREE OPERATIONS
ALGORITHM TO SEARCH A NODE
• Searching a node was part of the operation performed during insertion.
Algorithm to search an element from a binary search tree is given below.
1. Input the DATA to be searched and assign the address of the root node to ROOT.
2. If (DATA == ROOT → Info)
(a) Display “The DATA exist in the tree”
(b) GoTo Step 6
3. If (ROOT == NULL)
(a) Display “The DATA does not exist”
(b) GoTo Step 6
4. If(DATA > ROOT→Info)
(a) ROOT = ROOT→RChild
(b) GoTo Step 2
5. If(DATA < ROOT→Info)
(a) ROOT = ROOT→Lchild
(b) GoTo Step 2
6. Exit
BINARY SEARCH TREE OPERATIONS
ALGORITHM TO DELETE A NODE
• First search and locate the node to be deleted. Then any one of
the following conditions arises :
1. The node to be deleted has no children
2. The node has exactly one child (or sub tress, left or right sub
tree)
3. The node has two children (or two sub tress, left and right
sub tree)
 Node has no children
• Suppose the node to be deleted is N. If N has no children then
simply delete the node and place its parent node by the NULL
pointer.
BINARY SEARCH TREE OPERATIONS
ALGORITHM TO DELETE A NODE
 Node has one child
• If N has one child, check whether it is a right or left child.
• If it is a right child, then find the smallest element from the
corresponding right sub tree.
• Then replace the smallest node information with the deleted
node.
• If N has a left child, find the largest element from the
corresponding left sub tree.
• Then replace the largest node information with the deleted
node.
BINARY SEARCH TREE OPERATIONS
ALGORITHM TO DELETE A NODE
 Node has two children
• The same process is repeated if N has two children, i.e., left and
right child.
• Randomly select a child and find the small/large node and
replace it with deleted node.
• NOTE: The tree that we get after deleting a node should also be
a binary search tree.
BINARY SEARCH TREE OPERATIONS
DELETE A NODE
• If we want to delete 75 from the tree, following steps are
obtained :

Step 1: Assign the data to be deleted in DATA and NODE = ROOT.


Step 2: Compare the DATA with ROOT node, i.e., NODE,
information of the tree.
Since (50 < 75)
NODE = NODE → RChild
BINARY SEARCH TREE OPERATIONS
DELETE A NODE
Step 3: Compare DATA with NODE. Since
(75 = 75) searching successful. Now we
have located the data to be deleted, and
delete the DATA.
Step 4: Since NODE (i.e., node where
value was 75) has both left and right child
choose one.
(Say Right Sub Tree) - If right sub tree is
opted then we have to find the smallest
node.
But if left sub tree is opted then we have
to find the largest node.
BINARY SEARCH TREE OPERATIONS
DELETING A NODE
Step 5: Find the smallest element from
the right sub tree (i.e., 80) and replace
the node with deleted node.

Step 6: Again the (NODE → Rchild is not


equal to NULL) find the smallest element
from the right sub tree (Which is 85) and
replace it with empty node.

Step 7: Since
(NODE→Rchild = NODE→Lchild = NULL)
delete the NODE and place NULL in the
parent node.
Step 8: Exit.
BINARY SEARCH TREE OPERATIONS
ALGORITHM TO DELETE A NODE
• NODE is the current position of the tree, which is in under
consideration. LOC is
• the place where node is to be replaced. DATA is the information of
node to be deleted.
1. Find the location NODE of the DATA to be deleted.
2. If (NODE = NULL)
(a) Display “DATA is not in tree”
(b) Exit
3. If(NODE → Lchild = NULL)
(a) LOC = NODE
(b) NODE = NODE → RChild
4. If(NODE → RChild= =NULL)
(a) LOC = NODE
(b) NODE = NODE → LChild
BINARY SEARCH TREE OPERATIONS
ALGORITHM TO DELETE A NODE
5. If((NODE → Lchild not equal to NULL) && (NODE → Rchild not equal to
NULL))
(a) LOC = NODE → RChild
6. While(LOC → Lchild not equal to NULL)
(a) LOC = LOC → Lchild
7. LOC → Lchild = NODE → Lchild
8. LOC → RChild= NODE → RChild
9. Exit
BST implementation using C++
# include <iostream>
# include <cstdlib>

using namespace std;

/* Node Declaration */
struct node
{
int info;
node *left;
node *right;
}*root;
BST implementation using C++
/* Class Declaration */
class BST
{ public:
void find(int, node **, node **);
void insert(node *, node *);
void del(int);
void case_a(node *,node *);
void case_b(node *,node *);
void case_c(node *,node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
void display(node *, int);
BST(){ root = NULL; }
};
BST implementation using C++
/* Main Contains Menu */
int main()
{
int choice, num;
BST *bst;
node *temp;
while (1)
{
cout<<"-----------------"<<endl;
cout<<"Operations on BST"<<endl;
cout<<"-----------------"<<endl;
cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Inorder Traversal"<<endl;
cout<<"4.Preorder Traversal"<<endl;
BST implementation using C++
/* Main Contains Menu */
cout<<"5.Postorder Traversal"<<endl;
cout<<"6.Display"<<endl;
cout<<"7.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
temp = new node;
cout<<"Enter the number to be inserted : ";
cin>>temp->info;
bst->insert(root, temp);
break;
BST implementation using C++
/* Main Contains Menu */
case 2:
if (root == NULL)
{ cout<<"Tree is empty, nothing to delete"<<endl;
continue;
}
cout<<"Enter the number to be deleted : ";
cin>>num;
bst->del(num);
break;
case 3:
cout<<"Inorder Traversal of BST:"<<endl;
bst->inorder(root);
cout<<endl;
break;
BST implementation using C++
/* Main Contains Menu */
case 4:
cout<<"Preorder Traversal of BST:"<<endl;
bst->preorder(root);
cout<<endl;
break;
case 5:
cout<<"Postorder Traversal of BST:"<<endl;
bst->postorder(root);
cout<<endl;
case 7:
break; exit(1);
case 6: default:
cout<<"Display BST:"<<endl; cout<<"Wrong choice"<<endl;
}
bst->display(root,1); }
cout<<endl; return 0;
break; }
BST implementation using C++
/* Inserting Element into the Tree */
void BST::insert(node *tree, node *newnode)
{
if (root == NULL)
{
root = new node;
root->info = newnode->info;
root->left = NULL;
root->right = NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree->info == newnode->info)
{
BST implementation using C++
cout<<"Element already in the tree"<<endl;
return;
}
if (tree->info > newnode->info)
{
if (tree->left != NULL)
{
insert(tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
BST implementation using C++
cout<<"Node Added To Left"<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert(tree->right, newnode);
}
BST implementation using C++
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<"Node Added To Right"<<endl;
return;
}
}
}
BST implementation using C++
/* Pre Order Traversal */
void BST::preorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
cout<<ptr->info<<" ";
preorder(ptr->left);
preorder(ptr->right);
}
}
BST implementation using C++
/* In Order Traversal */
void BST::inorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
inorder(ptr->left);
cout<<ptr->info<<" ";
inorder(ptr->right);
}
}
BST implementation using C++
/* Postorder Traversal */
void BST::postorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
postorder(ptr->left);
postorder(ptr->right);
cout<<ptr->info<<" ";
}
}
PREORDER TRAVERSAL NON-RECURSIVELY
• The preorder traversal non-recursively algorithms uses a variable
PN (Present Node), which will contain the location of the node
currently being scanned.
• Left(R) denotes the left child of the node R and Right(R) denoted
the right child of R.
• A stack is used to hold the addresses of the nodes to be
processed.
• Info(R) denotes the information of the node R.
• Preorder traversal starts with root node of the tree i.e., PN =
ROOT
PREORDER TRAVERSAL NON-RECURSIVELY

Step 1: Process the node PN. If any right child is there for PN, push
the Right (PN) into the top of the stack and proceed down to
left by PN = Left (PN), if any left child is there
Repeat the step 1 until there is no left child (i.e., Left (PN) =
NULL).
Step 2: Now we have to go back to the right node(s) by backtracking
the tree. This can be achieved by popping the top most
element of the stack. Pop the top element from the stack
and assigns to PN.
Step 3: If (PN is not equal to NULL) go to the Step 1
Step 4: Exit
PREORDER TRAVERSAL NON-RECURSIVELY
• ALGORITHM
• An array STACK is used to hold the addresses of nodes.
• TOP pointer points to the top most element of the STACK.
• ROOT is the root node of tree to be traversed.
• PN is the address of the present node under scanning.
• Info(PN) if the information contained in the node PN.

1. Initialize TOP = NULL, PN = ROOT 6. Else


2. Repeat step 3 to 5 until (PN = NULL) (a) PN = STACK[TOP]
(b) TOP = TOP–1
3. Display Info(PN)
7. Exit
4. If (Right(PN) not equal to NULL)
(a) TOP = TOP+1
(b) STACK(TOP) = Right(PN);
5. If(Left(PN) not equal to NULL)
(a) PN = Left(PN)
PREORDER TRAVERSAL NON-RECURSIVELY
• Example:
PREORDER TRAVERSAL NON-RECURSIVELY
• Example:
PREORDER TRAVERSAL NON-RECURSIVELY
IN ORDER TRAVERSAL NON-RECURSIVELY
• The in-order traversal algorithm uses a variable PN, which will contain the
location of the node currently being scanned.
• Info (R) denotes the information of the node R, Left(R) denotes the left
child of the node R and Right (R) denotes the right child of the node R.
• In-order traversal starts from the ROOT node of the tree (i.e., PN = ROOT).
• Then repeat the following steps until PN = NULL :

Step 1: Proceed down to left most node of the tree by pushing the root node
onto the stack.
Step 2: Repeat the step 1 until there is no left child for a node.
Step 3: Pop the top element of the stack and process the node. PN =
STACK[TOP]
Step 4: If the stack is empty then go to step 6.
Step 5: If the popped element has right child then PN = Right(PN). Then
repeat the step from 1.
Step 6: Exit.
IN ORDER TRAVERSAL NON-RECURSIVELY
• ALGORITHM
• An array STACK is used to temporarily store the addresses of the nodes.
TOP pointer always points to the topmost element of the STACK.

1. Initialize TOP = NULL and PN = ROOT 11. PN = STACK[TOP]


2. Repeat the Step 3, 4 and 5 until (PN = NULL) 12. TOP =TOP –1
3. TOP = TOP +1 13. Exit
4. STACK[TOP] = PN
5. PN = Left(PN)
6. PN = STACK[TOP]
7. TOP = TOP–1
8. Repeat steps 9, 10, 11 and 12 until (PN = NULL)
9. Display Info(PN)
10. If(Right(PN) is not equal to NULL
(a) PN = Right(PN)
(b) Go to Step 6
IN ORDER TRAVERSAL NON-RECURSIVELY
• Example
IN ORDER TRAVERSAL NON-RECURSIVELY
• Example
IN ORDER TRAVERSAL NON-RECURSIVELY
• Example
POST ORDER TRAVERSAL NON-RECURSIVELY
• The post-order traversal algorithm uses a variable PN, which will
contain the location of the node currently being scanned.
• Left (R) denotes the left child of the node R and Right(R) denotes the
right child of the node R.
• Info (R) denotes the information of the node R.
• The post-order traversal algorithm is more complicated than the
proceeding two algorithms, because here we have to push the
information of the node PN to stack in two different situations.
• These two situations are distinguished between by pushing Left(PN) and
- Right(PN) on to stack.
• That is whenever a negative node sees in the stack; it means that it was
a right child of a node.
• Post-order traversal starts from the ROOT node of the tree (i.e., PN =
ROOT).
POST ORDER TRAVERSAL NON-RECURSIVELY

Step 1: Proceed down to left most node of the tree by pushing the
root node and -Right(PN) on the stack.
Step 2: Repeat the Step 1 until there is no left child for the node.
Step 3: Pop and display the positive nodes on the stack.
Step 4: If the stack is empty, go to Step 6
Step 5: If a negative node is popped, then PN = – PN (i.e., to remove
the negative sign in the node) and go to Step 1.
Step 6: Exit.
POST ORDER TRAVERSAL NON-RECURSIVELY
• ALGORITHM
• An array STACK is used to temporarily store the addresses of the nodes.
• TOP pointer always points to the top most element of the stack.
1. Initialize TOP = NULL and PN = ROOT
2. Repeat the steps 3 to 6 until (PN = NULL)
3. TOP = TOP+1 9. Repeat the step 9 until (PN less
4. SATCK(TOP)=PN than or equal to 0)
(a) Display Info(PN)
5. If (Right(PN) is not equal to NULL) (b) PN = STACK(TOP)
(a) TOP = TOP+1 (c) TOP = TOP-1
(b) STACK(TOP) = – Right(PN) 10. If(PN < 0)
6. PN = Left(PN) (a) PN = – PN
7. PN = STACK(TOP) (b) Go to step 2
11. Exit
8. TOP = TOP–1
POST ORDER TRAVERSAL NON-RECURSIVELY
• Example
POST ORDER TRAVERSAL NON-RECURSIVELY
• Example
POST ORDER TRAVERSAL NON-RECURSIVELY
• Example
POST ORDER TRAVERSAL NON-RECURSIVELY
• Example
Binary Expression Trees
• An application of binary trees
• Expression types: Infix, Prefix and Postfix
• There are total of 6 conversion:
– Infix to Prefix
– Infix to Postfix
– Prefix to Infix
– Prefix to Postfix
– Postfix to Infix
– Postfix to Infix
• Conversion can be done using two methods:
– Using Stack.
– Using Expression tree.
• Conversion by using Expression tree is quite easy and fast as
compared to other one.
Binary Expression Trees
• An expression tree for an arithmetic, relational, or logical
expression is a binary tree in which:

• The parentheses in the expression do not appear.


• The leaves are the variables or constants in the expression.
• The non-leaf nodes are the operators in the expression:

• A node for a binary operator has two non-empty subtrees.


• A node for a unary operator has one non-empty subtree.

• The operators, constants, and variables are arranged in such a


way that an inorder traversal of the tree produces the original
expression without parentheses.
Binary Expression Trees
• Examples:

+
a 3

+
3 -
* +
4 5 9 6
log

n
Why Binary Expression Trees?
• Expression trees are used to remove ambiguity in expressions.
• Consider the algebraic expression 2 - 3 * 4 + 5.
• Without the use of precedence rules or parentheses, different
orders of evaluation are possible:

((2-3)*(4+5)) = -9
((2-(3*4))+5) = -5
(2-((3*4)+5)) = -15
(((2-3)*4)+5) = 1
(2-(3*(4+5))) = -25

• The expression is ambiguous because it uses infix notation: each


operator is placed between its operands.
Why Binary Expression Trees?
• Storing a fully parenthesized expression, such as ((x+2)-(y*(4-z))), is
wasteful, since the parentheses in the expression need to be stored to
properly evaluate the expression.
• A compiler will read an expression in a language like Java, and
transform it into an expression tree.
• Expression trees impose a hierarchy on the operations in the
expression.
• Terms deeper in the tree get evaluated first.
• This allows the establishment of the correct precedence of operations
without using parentheses.
• Expression trees can be very useful for:
• Evaluation of the expression.
• Generating correct compiler code to actually compute the
expression's value at execution time.
• Performing symbolic mathematical operations (such as
differentiation) on the expression.
Binary Expression Trees
• Expression tree is a special kind of binary tree in which:
1. Each leaf node represents an operand.
2. Each non-leaf node represents a single binary operator.
3. The left and right sub-trees of an operator node represent sub-
expressions that must be evaluated before applying the
operator at the root of the sub-tree.
Binary Expression Trees
• Level in expression tree Indicate Precedence.
• The levels of the nodes in the tree indicate their relative
precedence of evaluation. Parentheses are not required
to indicate precedence.
• Operations at higher levels of the tree are evaluated later
than those below them.
• The operation at the root is always performed last.
• Infix Notation for above expression tree is given as:
4–3+6*5/2
• Operator deep in the expression tree are evaluated
first so given expression is evaluated as:
4 – 3 + ( (6*5) / 2 ) = 1 + 15 = 16
• So from above we can see that operator at lower
level have high precedence and operator at higher
level have low precedence.
• Operator having higher precedence are evaluated
first.
Binary Expression Trees

• Preorder Traversal [Root L R] : + - / + A B * C D * E – F G H


• In-order Traversal is [L Root R] : A + B / C * D – E * F – G + H
• Postorder Traversal [L R Root] : A B + C D * / E F G - * - H +
Binary Expression Trees
• Procedure to convert from one notation to other notation.
Binary Expression Trees
• Constructing expression tree using Infix expressions
• Steps:
1. Number the operators in the in the infix notation according to their
order of priority
2. Create the binary tree by adding nodes of lower priority
3. Add children to the nodes according to the order of appearance of
operand in the expression.
• Examples
a. x / y + a – b * c b. 4 ^ 2 * 3 - 3 + 8 / 4 / (1 + 1)
Postfix to Binary Expression Tree
Algorithm
1. Create a Stack
2. Read next input symbol
3. If the symbol is a numeric value or a variable, create a new
expression tree with a single node representing the
value/variable and push it into the stack.
4. If the symbol is an operator, pop out two trees (T1 and T2) from
the stack. Create a new tree with the operator as the root and
T1 and T2 as two children. Push this new tree back into the
stack.
5. Repeat this procedure until the whole input is read.
6. At the end, the stack will contain a single tree which would be
the output.
Postfix to Expression Tree Construction

• ab+cde+**
stack
Postfix to Expression Tree Construction

• ab+cde+**
top
If symbol is an
operand, put it
a b in a one node
tree and push
it on a stack.
Postfix to Expression Tree Construction

• ab+cde+**
If symbol is an
operator, pop two
trees from the stack,
+ form a new tree with
operator as the root
a b and T1 and T2 as left
and right subtrees and
push this tree on the
stack.
Postfix to Expression Tree Construction

• ab+cde+**

+ c d e

a b
Postfix to Expression Tree Construction

• ab+cde+**

+ c +

a b d e
Postfix to Expression Tree Construction

• ab+cde+**

+ *

a b c
+

d e
Postfix to Expression Tree Construction

• ab+cde+**

+ *

a b c
+

d e
Infix to Expression Tree Construction
• First convert infix expression to postfix or prefix form, the construct binary tree
• Alternatively use to stack i.e. one for operand and another for operator
• Write an algorithm and program for the
following sorting:
a. Insertion sort
b. Quick sort
c. Merge sort
d. Heap sort
e. Radix sort,

Potrebbero piacerti anche