Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
• 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.
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>
/* 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.
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.
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:
+
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
• 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,