0% found this document useful (0 votes)
21 views114 pages

Module 4 DS

This document discusses different tree data structure concepts including binary trees. It defines key tree terminology such as root, child, parent, leaf, internal and external nodes. It also covers tree representations including list representation, left child-right sibling representation and binary tree representation. Binary trees are defined as a special type of tree where each node has a maximum of two children.

Uploaded by

iliyaz pasha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views114 pages

Module 4 DS

This document discusses different tree data structure concepts including binary trees. It defines key tree terminology such as root, child, parent, leaf, internal and external nodes. It also covers tree representations including list representation, left child-right sibling representation and binary tree representation. Binary trees are defined as a special type of tree where each node has a maximum of two children.

Uploaded by

iliyaz pasha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 114

R L JALAPPA INSTITUTE OF TECHNOLOGY

Dept.. of Computer Science & Engg.

Module 4

Manjunatha B N
Assistant Professor

Department
1 of Computer Science, RLJIT
Outline
 Terminology
 Binary Trees
 Properties of Binary trees
 Array and linked Representation of Binary Trees
 Binary Tree Traversals - Inorder, postorder, preorder
 Additional Binary tree operations
 Threaded binary trees
 Binary Search Trees :Definition, Insertion, Deletion,
Traversal, Searching
 Application of Trees-Evaluation of Expression
 Programming Examples

Department of Computer Science, RLJIT 2


INTRODUCTION
• In linear data structure, data is organized in sequential order and
in non-linear data structure, data is organized in random order.

• Tree is a very popular data structure used in wide range of


applications.

• A tree data structure can be defined as follows...


• Tree is a non-linear data structure which organizes data in
hierarchical fashion and the tree structure follows a recursive
pattern of organizing and storing data.

• Every individual element is called as Node.

Department of Computer Science, RLJIT 3


• Node in a tree data structure, stores the actual data of that
particular element and link to next element in hierarchical
structure.
• If there are N number of nodes in a tree structure
• Then there can be a maximum of N-1 number of links
Department of Computer Science, RLJIT 4
What is a tree?
Definition: A tree is a set of finite set of one or more nodes that shows
parent-child relation such that:
 There is a special node called the root node.
 The remaining nodes are partitioned into disjoint subsets T1, T2,
T3,……..Tn, n>=0 where T1, T2, T3……Tn which are all
children of root node are themselves trees called subtrees.

Example: Consider the following tree. Let us identify the root node
and various subtrees:
 The tree has 8 nodes: A, B, C, D, E, F,
G and H.
 The node A is the root of the tree.
 We normally draw the trees with root
at the top.
 The node B, C and D are the children
of node A and hence there are 3
subtrees identified by B, C and D.
Department of Computer Science, RLJIT
 The node A is the parent 5
of B, C and D.
Terminology
Root
• In a tree data structure, the first node is called as Root Node.
• Every tree must have root node.
• We can say that root node is the origin of tree data structure.
• In any tree, there must be only one root node.
• We never have multiple root nodes in a tree.
• Ex: „A‟ in the below tree.

Department of Computer Science, RLJIT 6


Edge
• In a tree data structure, the connecting link between any two nodes
is called as EDGE.

• In a tree with 'N' number of nodes there will be a maximum of 'N-1'


number of edges.

• Ex: Line between two nodes.

Department of Computer Science, RLJIT 7


Parent
• In a tree data structure, the node which is predecessor of any
node is called as PARENT NODE.
• In simple words, the node which has branch from it to any other
node is called as parent node.
• Parent node can also be defined as "The node which has child /
children".
• Ex: A,B,C,E & G are parent nodes.
Child
• In a tree data structure, the node which is descendant of any node
is called as CHILD Node.
• In simple words, the node which has a link from its parent node is
called as child node.
• In a tree, any parent node can have any number of child nodes.
• In a tree, all the nodes except root are child nodes.
• Ex: B & C are children of A, G & H are children of C and K child of
G.
Siblings
• In a tree data structure, nodes which belong to same Parent
are called as SIBLINGS.
• In simple words, the nodes with same parent are called as
Sibling nodes.
• Ex: B & C are siblings, D, E and F are siblings, G & H are
siblings, I & J are siblings.
Leaf
• In a tree data structure, the node which does not have a
child is called as LEAF Node.
• In simple words, a leaf is a node with no child. In a tree data
structure, the leaf nodes are also called as External Nodes.
• External node is also a node with no child. In a tree, leaf node
is also called as 'Terminal' node.
• Ex: D,I,J,F,K AND H are leaf nodes.
Internal Nodes
• In a tree data structure, the node which has at least one child is
called as INTERNAL Node.
• In simple words, an internal node is a node with at least one child.
• In a tree data structure, nodes other than leaf nodes are called as
Internal Nodes.
• The root node is also said to be Internal Node if the tree has more
than one node.
• Internal nodes are also called as 'Non-Terminal' nodes.
• Ex: A,B,C,E & G
Degree of a node
• In a tree data structure, the total number of children of a node is
called as DEGREE of that Node.
• In simple words, the Degree of a node is total number of children it
has.
• The highest degree of a node among all the nodes in a tree is called
as 'Degree of Tree'.
• Ex: Degree of B is 3, A is 2 and of F is 0
Level of a node
• In a tree data structure, the root node is said to be at Level 0 and the
children of root node are at Level 1 and the children of the nodes
which are at Level 1 will be at Level 2 and so on...
• In simple words, in a tree each step from top to bottom is called as a
Level and the Level count starts with '0' and incremented by one at
each level (Step).
Height
• In a tree data structure, the total number of edges from
leaf node to a particular node in the longest path is called
as HEIGHT of that Node.
• In a tree, height of the root node is said to be height of the tree.
In a tree, height of all leaf nodes is '0'
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'.
Path
• In a tree data structure, the sequence of Nodes and Edges
from one node to another node is called as PATH between
the two Nodes.
• Length of a Path is total number of nodes in that path.
• In below example the path A - B - E - J has length 4.
Sub Tree
• In a tree data structure, each child from a node forms a
subtree recursively.
• Every child node will form a subtree on its parent node.
Tree Representations
A general Tree Structure can be represented with the following three
methods.

– List Representation

– Left Child - Right Sibling Representation

– Degree two Representation (Binary Tree Representation)


List Representation:-
 The root node comes first.
 It is immediately followed by a list of sub trees of that node.
 It is recursively repeated for each sub tree.

a) Tree b) List Representation

 The tree in the above figure could be written as the list


(A(B(D,E(I,J),F),C(G(K),H)) – list representation (with rounded brackets).
 The information in the root node comes first followed by a list of the subtrees of
that node.
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
» Right sibling reference field
• Graphical representation of that node is as follows...

• Data field stores the actual value of a node


• Left reference field stores the address of the left child otherwise
stores NULL.
• Right reference field stores the address of the right sibling node
otherwise stores NULL.
a) tree

b) left-child right –sibling representation


Degree two tree (Binary Tree) :-
• The left child-right sibling representation can be converted to a degree two tree
by simply rotating the right sibling pointers clockwise by 45 degrees.
• In this representation, the two children of a node are called the left child and the
right child.
• It is equivalent to converting a normal tree to binary tree.
• Degree two trees or left child-right child trees are nothing but binary trees.

a) The left child-right sibling


representation b) Degree two tree(Binary Tree)
representation
Degree two tree (Binary Tree) :-
• The left child-right sibling representation can be converted to a degree two tree
by simply rotating the right sibling pointers clockwise by 45 degrees.
• In this representation, the two children of a node are called the left child and the
right child.
• It is equivalent to converting a normal tree to binary tree.
• Degree two trees or left child-right child trees are nothing but binary trees.

a) The left child-right sibling


representation b) Degree two tree(Binary Tree)
representation
Binary Tree:-
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.

Note: In a binary tree, every node can have either 0 children or 1


child or 2 children but not more than 2 children.

Example:
Properties of Binary Tree:-
(i) The maximum number of nodes on level i of a binary tree = 2i for i>=0.
(ii) The maximum number of nodes in a binary tree of depth k = 2k – 1.
Proof: Consider the following binary tree and observe the following factors:
Number of nodes at level 0 = 1 = 20
Number of nodes at level 1 = 2 = 21
Number of nodes at level 2 = 4 = 22
.
.
.
Number of nodes at level i = 2i
Therefore, total number of nodes in the full binary tree of level
i = 20 +21 + 22 + 23 + ….. + 2i
The above series is a geometric progression whose sum is given by:
S = a (rn -1) / (r - 1)
Where a=1, n=i+1, and r=2
Therefore, Total number of nodes nt = a (rn – 1) / (r – 1)
= 1(2i+1 -1) /(2 – 1)
= 2i+1 -1
The depth of the tree k is maximum level + 1, so k = i+1
Substituting this value in above equation, we get nt = 2k -1
Lemma 2: [Relation between number of leaf nodes and degree-2 nodes]:
For any nonempty binary tree, T, if n0 is the number of leaf nodes
and n2 the number of nodes of degree 2, then n0 = n2 + 1.

Proof: Let n1 be the number of nodes of degree one and n the total number
of nodes.
Since all nodes in T are at most of degree two, we have
n = n 0 + n 1+ n 2 (1)
Count the number of branches in a binary tree. If B is the number of
branches, then
n =B + 1
All branches stem from a node of degree one or two. Thus,
B =n 1+ 2n2
Hence, we obtain
n = B + 1= n 1+ 2n2 + 1 (2)

Subtracting Eq. (2) from Eq. (1) and rearranging terms, we get

n0 = n2 +1
Types of Binary Trees

• Strictly Binary Tree

• Complete Binary Tree

• Almost complete Binary Tree

• Right Skewed BT

• Left Skewed BT

• Extended Binary Tree

• Binary Search Tree(BST


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 strictly Binary Tree can be defined as follows...

• 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 or 2-Tree.
Complete Binary Tree
• In complete binary tree all the nodes must have exactly two
children and at every level of complete binary tree there must be
2level number of 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.


For example : At level 2 there must be 2^2 = 4 nodes and
At level 3 there must be 2^3 = 8 nodes.
Almost complete Binary Tree
• It is complete binary tree but completeness property
is not followed in last level.
• In the below tree absence of leaf nodes L, M, N, O
and P indicates its almost complete binary tree.
Right Skewed BT
Here the tree grows only towards right.

Left Skewed BT
Here the tree grows only towards left.
Extended Binary Tree

• A binary tree can be converted into Full Binary tree by


adding dummy nodes to existing nodes wherever
required.

• The full binary tree obtained by adding dummy nodes to a


binary tree is called as Extended Binary Tree.
Binary Search Tree(BST)

• BST is a binary tree with a difference that for any node x


» data of left subtree < data(x)

» data of right subtree >= data(x).

• The above condition should be satisfied by all the nodes.


Binary Tree Representations
• A binary tree data structure is represented using two
methods. Those methods are as follows...
» Array Representation

» Linked List Representation.


Array Representation
• In array representation of binary tree, we use a one
dimensional array (1-D Array) to represent a binary tree.
• Consider the above example of binary tree and it is
represented as follows...
• To represent a binary tree of depth 'n' using array representation, we
need one dimensional array with a maximum size of 2^n+1 - 1.

• For any node with the position i,

• 2i + 1 gives the position of the left child

• 2i + 2 gives the positon of the right child.

• Parent node position is identified by using formula (i-1) / 2.

• If i is the position of the left child i+1 gives the position of right
child.
Advantages of array representation

» Faster access

» Easy for implementation

» Good for complete binary trees

Disadvantages

» Wastes memory for skewed trees

» Implementation of operations requires rearranging

(shifting)of array elements


Linked List Representation
• The linked notation uses a doubly 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.

» Third for storing right child address.

• In this linked list representation, a node has the following structure...


struct node
{
int info;
struct node *llink,rlink;
};
typedef struct node * NODE;
Binary Tree Traversals
• Tree traversal is a method of visiting each nodes of a tree exactly once in a

systematic order.

• During traversal, one may print the info field of each node visited.

• There are three types of binary tree traversals.

1. In - Order Traversal

2. Pre - Order Traversal

3. Post - Order Traversal


In - Order Traversal ( leftChild - root - rightChild )

• 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
» 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.
In - Order Traversal ( leftChild - root - rightChild )
• In order traversal can be represented as:
(i) Traverse the left subtree (L)
(ii) Process the root node (N)
(iii) Traverse the right subtree (R)
Function:
void inorder(NODE root)
{
if (root != NULL)
{
inorder(root->llink);
printf("%d\t", root->info);
inorder(root->rlink);
}
}
In-Order Traversal for above example of binary tree is

I-D-J-B-F-A-G-K-C-H
Pre - Order Traversal ( root - leftChild - rightChild )

• In Pre-Order traversal, the root node is visited before left child


and right child nodes.

• In this traversal:
» The root node is visited first,

» Then its left child

» Later its right child.

• This pre-order traversal is applicable for every root node of all


subtrees in the tree.
Pre - Order Traversal ( root - leftChild - rightChild )
• Preorder traversal can be represented as:
(i) Process the root node (N)
(ii) Traverse the left subtree (L)
(iii) Traverse the right subtree (R)
Function:
void preorder(NODE root)
{
if (root != NULL)
{
printf("%d\t", root->info);
preorder(root->llink);
preorder(root->rlink);
}
}
Pre-Order Traversal for above example binary tree is

A-B-D-I-J-F-C-G-K-H
Post - Order Traversal ( leftChild - rightChild - 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
» Then its root node.

• This is recursively performed until the right most node is


visited.
Post - Order Traversal ( leftChild - rightChild - root )
• Postorder traversal can be represented as:
(i) Traverse the left subtree (L)
(ii) Traverse the right subtree (R)
(iii) Process the root node (N)
Function:
void postorder(NODE root)
{
if (root != NULL)
{
postorder(root->llink);
postorder(root->rlink);
printf("%d\t", root->info);
}
}
Post-Order Traversal for above example binary tree is
I-J-D-F-B-K-G-H-C-A
Iterative Inorder Traversal
• Traversal techniques using recursion consumes system
stack space .

• The stack space used may not be acceptable for


unbalanced trees of trees of larger heights.

• IN such cases, iterative traversal can be implemented by


simulating stack space with the help of an array.

• Another solution is to use threaded binary trees during


traversal.
void iterative inorder(node *root)
{
node *cur = root;
while(1)
{
while(cur!=NULL)
{
push(cur);
cur=cur->leftptr;
}
if(top == -1)
break;
cur = pop();
printf(“%d “, cur->data);
cur=cur->rightptr;
}
}
Building Binary Tree from Traversal Pairs

• Sometimes it is required to construct a binary tree if its


traversals are known.
• From a single traversal it is not possible to construct
unique binary tree.
• However any of the two traversals are given then the
corresponding tree can be drawn uniquely:
 Inorder and preorder
 Inorder and postorder
 Inorder and level order
The basic principle for formulation is as follows:

• If the preorder traversal is given, then the first node is the root
node.

• If the postorder traversal is given then the last node is the root
node.

• Once the root node is identified, all the nodes in the left sub-trees
and right sub-trees of the root node can be identified using
inorder.

• Same technique can be applied repeatedly to form sub-trees.


• It can be noted that, for the purpose mentioned, two
traversal are essential out of which one should be
inorder traversal and another preorder or postorder.

• Alternatively, given preorder and postorder traversals,


binary tree cannot be obtained uniquely.
Example 1:
• Construct a binary tree from a given preorder and inorder sequence:
• Preorder: A B D G C E H I F
• Inorder: D G B A H E I C F
Solution:
• From Preorder sequence A B D G C E H I F:
– The root is: A
• From Inorder sequence D G B A H E I C F, we get:
– Left sub tree is: D G B
– Right sub tree is: H E I C F
To find the root, left and right sub trees for D G B:
• From the preorder sequence B D G, the root of tree is: B
• From the inorder sequence D G B,
• we can find that D and G are to the left of B.
• The Binary tree upto this point looks like:
To find the root, left and right sub trees for D G:

• From the preorder sequence D G, the root of the tree is: D

• From the inorder sequence D G, we can find that there is


no left node to D and G is at the right of D.

• The Binary tree upto this point looks like


• To find the root, left and right sub trees for H E I C F:

• From the preorder sequence C E H I F, the root of the left sub tree

is: C

• From the inorder sequence H E I C F, we can find that H E I are at

the left of C and F is at the right of C.

• The Binary tree upto this point looks like:


• To find the root, left and right sub trees for H E I:

• From the preorder sequence E H I, the root of the tree is: E

• From the inorder sequence H E I, we can find that H is at the

left of E and I is at the right of E.

• The Binary tree upto this point looks like


Example 2: Construct a binary tree from a given preorder and inorder sequence:
preorder: ABCDEFGHI
inorder: B CAE D G H F I

A A

B, C D, E, F, G, H, I B D

A
C E F

B D, E, F, G, H, I G I

C H

CHAPTER 5 67
Additional Binary Tree Operations:

Function to copy a tree


NODE copy (NODE root)
{
NODE temp;
if (root == NULL)
return NULL;
temp = (NODE *) malloc (sizeof(NODE));
temp->info = root->info;
temp->lptr = copy(root->lptr);
temp->rptr = copy(root->rptr);
return temp;
}
Function to check whether two trees are equal or not (Test
Equality of two trees)
int equal (NODE r1, NODE r2)
{
if(r1==NULL && r2==NULL)
return 1;
if(r1==NULL && r2!=NULL)
return 0;
if(r1!=NULL && r2==NULL)
return 0;
if(r1->info != r2->info)
return 0;
if(r1->info == r2->info)
return 1;
return equal(r1->llink, r2->llink) && equal(r1->rlink, r2->rlink);
}
Disadvantages of Binary Tree

1. More than 50% of linked fields have NULL (\0) values, hence
more memory space is wasted.

2. Traversing is time consuming, because stack is used for both


recursive and non - recursive programs. Time is wasted in
push and pop activities.

3. Only downward movements are possible.

4. Computations of predecessor and successor of given nodes is


time consuming.

All these disadvantages can be overcome using Threaded Binary


Trees.
Threaded binary trees
• A binary tree is represented using array representation or
linked list representation.

• When a binary tree is represented using linked list


representation, if any node is not having a child we use NULL
pointer in that position.

• In any binary tree linked list representation, there are more


number of NULL pointer than actual pointers.
• Generally, in any binary tree linked list representation, if there
are 2N number of reference fields, then N+1 number of
reference fields are filled with NULL ( N+1 are NULL out of
2N ).

• This NULL pointer does not play any role except indicating
there is no link (no child).
• A. J. Perlis and C. Thornton have proposed new binary tree
called "Threaded Binary Tree", which make use of NULL
pointer to improve its traversal processes.

• In threaded binary tree, NULL pointers are replaced by


references to other nodes in the tree, called threads.
• Threaded Binary Tree is also a binary tree in which all left
child pointers that are NULL (in Linked list representation)
points to its in-order predecessor.
» LEFT -> in-order predecessor.

• All right child pointers that are NULL (in Linked list
representation) points to its in-order successor.

• If there is no in-order predecessor or in-order successor, then it


points to root node.
» RIGHT -> in-order successor
Consider the following binary tree...

In-order traversal of above binary tree...

H-D-I-B-E-A-F-J-C-G
When we represent above binary tree using linked list representation
Binary Search Tree
• In a binary tree, every node can have maximum of two
children but there is no order of nodes based on their values.

• In binary tree, the elements are arranged as they arrive to the


tree, from top to bottom and left to right.

• A binary tree has the following time complexities...

» Search Operation - O(n)

» Insertion Operation - O(1)

» Deletion Operation - O(n)


• To enhance the performance of binary tree, we use special type
of binary tree known as Binary Search Tree.

• Binary search tree mainly focus on the search operation in


binary tree.

• Every Binary Search Tree is a binary tree but all the Binary
Trees need not to be binary search trees.

• Binary search tree can be defined as follows...


• Binary Search Tree is a binary tree in which every node
contains only smaller values in its left subtree and only larger
values in its right subtree.
Operations on a Binary Search Tree

• The following operations are performed on a binary search


tree...

» Search
» Insertion
» Deletion
» Traversal
Search Operation in BST
In a binary search tree, the search operation is performed with O(log n)
time complexity.
• The search operation is performed as follows...

Step 1: Read the search element from the user


Step 2: Compare, the search element with the value of root node in the
tree.

Step 3: If both are matching, then display "Given node found!!!" and
terminate the function

Step 4: If both are not matching, then check whether search element is
smaller or larger than that root node value.
Step 5: If search element is smaller, then continue the search
process in left subtree
Step 6: If search element is larger, then continue the search
process in right subtree.
Step 7: Repeat the same until we find exact element or we
completed with a leaf node
Step 8 : If we reach the node with search value, then display
“Element is found” and terminate the function.
Step 9: If we reach a leaf node and it is also not matching
the display “Element not found” and terminate the function.
Function to search in BST
NODE search(NODE root, int key)
{
NODE cur;
if(root == NULL)
return NULL;
cur = root;
while(cur != NULL)
{
if(key == cur->info)
return cur;
if(key<cur->info)
cur = cur->llink;
else
cur = cur->rlink;
}
return NULL;
}
Insertion Operation in BST
• In a binary search tree, the insertion operation is performed with

• O(log n) time complexity.

• In binary search tree, new node is always inserted as a leaf node.

• The insertion operation is performed as follows...

Step 1: Create a newNode with given value and set its left and right to
NULL.

Step 2: Check whether tree is Empty.

Step 3: If the tree is Empty, then set set root to newNode.


Step 4: If the tree is Not Empty, then check whether value of newNode
is smaller or larger than the node (here it is root node).

Step 5: If newNode is smaller than the node, then move to its left child.
If newNode is larger than or equal to the node, then move to its right
child.

Step 6: Repeat the above step until we reach to a leaf node (i.e, reach to
NULL).

Step 7: After reaching a leaf node, then insert the newNode as left child
if newNode is smaller that leaf else insert it as right child.
/* This function is for creating a binary search
tree */
NODE insert(NODE root) while(cur != NULL)
{ {
NODE temp, cur, prev; prev = cur;
int item; if (item< cur->info)
printf("\nEnter The Element "); cur = cur->llink;
scanf("%d", &item); else
temp = (NODE) malloc(sizeof(struct cur = cur->rlink;
BST));
}
temp->llink = NULL;
temp->rlink = NULL;
if (item <prev->info)
temp->info = item;
prev->llink = temp;
else
if (root == NULL)
prev->rlink = temp;
return temp;
return root;
prev = NULL;
}
cur = root;
Deletion Operation in BST

In a binary search tree, the deletion operation is performed with


O(log n) time complexity. Deleting a node from Binary search tree
has following three cases...

Case 1: Deleting a Leaf node (A node with no children)

Case 2: Deleting a node with one child

Case 3: Deleting a node with two children


Case 1: Deleting a leaf node
We use the following steps to delete a leaf node from BST...

Step 1: Find the node to be deleted using search operation

Step 2: Delete the node using free function (If it is a leaf) and
terminate the function.
Case 2: Deleting a node with one child

We use the following steps to delete a node with one child from BST...

Step 1: Find the node to be deleted using search operation

Step 2: If it has only one child, then create a link between its parent

and child nodes.

Step 3:Delete the node using free function and terminate the function
Case 3: Deleting a node with two children

We use the following steps to delete a node with two children from
BST...

Step 1: Find the node to be deleted using search operation

Step 2: If it has two children, then find the largest node in its left
subtree (OR) the smallest node in its right subtree.

Step 3: Swap both deleting node and node which found in above
step.
Step 4: Then, check whether deleting node came to case 1 or case 2

else goto steps 2

Step 5: If it comes to case 1, then delete using case 1 logic.

Step 6: If it comes to case 2, then delete using case 2 logic.

Step 7: Repeat the same process until node is deleted from the tree.
Example
Construct a Binary Search Tree by inserting the
following sequence of numbers...

10,12,5,4,20,8,7,15 and 13
Other operation on BST:
1. To find Maximum value in a BST.
NODE max (NODE root)
{
NODE cur;
if(root == NULL)
return root;
cur = root;
while(cur->rlink != NULL)
cur = cur->rlink;
return cur;
}
Other operation on BST:
2. To find Minimum value in a BST.
NODE min (NODE root)
{
NODE cur;
if(root == NULL)
return root;
cur = root;
while(cur->llink != NULL)
cur = cur->llink;
return cur;
}
Other operation on BST:
3. To find the height of the tree.
int height(NODE root)
{
if(root==NULL)
return -1;
else
return(1+max(height(root->llink),height(root->rlink);
}

int max(int a, int b)


{
return (a>b) ? a : b;
}
Other operation on BST:
4. To count the nodes in a tree.(here we can use any of the
traversal technique and increment the counter whenever a node
is visited.)

void count(NODE root)


{
int count=0;
if(root==NULL)
return ;
count(root->llink);
count ++;
count(root->rlink);
}
Other operation on BST:
5. To count the leaf nodes (i.e, terminal nodes) BST.
void countleaf(NODE root)
{
int count=0;
if(root==NULL)
return ;
countleaf(root->llink);
if(root->llink == NULL && root->rlink == NULL)
count ++;
countleaf(root->rlink);
}
Application of Trees: Evaluation of Expressions.
Expression Trees:
A sequence of operators and operands that reduces to a
single value is called as an expression.
Expression Tree: is a binary tree that satisfy the
following properties:
(i) Any leaf is an operand
(ii) The root and internal nodes are operators
(iii) The subtrees represent sub expressions with root of
the subtree as an operator.
How an Infix Expression can be expressed using
Expression Tree?
 An Infix expression consisting of operators and
operands can be represented using a binary tree with
root as the operator.
 The left and right sub trees are the left and right
operands of that operator.
 A node containing an operator is not a leaf whereas a
node containing an operand is a leaf.
Example: 1) A + B 2) A + B * C
Evaluation of Expression:
 In expression tree, whenever an operator is
encountered, evaluate the expression in the left subtree
and evaluate the expression in the right subtree and
perform the operation.
 The recursive definition is as:
Function for Evaluation of Expression:
float Eval (NODE root)
{
float num;
switch (root->info)
{
case „+‟ : return Eval(root->llink) + Eval(root->rlink);
case „-‟ : return Eval(root->llink) - Eval(root->rlink);
case „*‟ : return Eval(root->llink) * Eval(root->rlink);
case „/‟ : return Eval(root->llink) / Eval(root->rlink);
case „$‟:
case„^‟: return pow(Eval(root->llink), Eval(root->rlink);
default : if(isalpha(root->info))
{
printf(“%c”, root->info);
printf(“%f”,&num);
return num;
}
else
return root->info = „0‟;
}
}
Questions???
1) What is a tree? With suitable example, define: i) root node ii) child node iii)
Siblings iv) Degree v) leaf node vi) internal and external node vii) level viii)
height ix) Depth
2) Represent the tree given in fig. using: i. List representation ii. Left-child Right
sibling representation iii. Degree 2 (or binary tree) representation

3) Define the following (with examples) i. Binary tree ii. Complete binary tree iii.
Binary search tree iv. Strictly Binary Tree v. Skewed binary tree.
4) Explain binary tree using Array representation and linked representation. Which
representation is more suitable and why?
5) What is the meaning of traversing a tree? What are the different traversal
techniques of a binary tree? Department
0r Write the routines to traverse the given string
of Computer Science, RLJIT 111
using i. Pre-order traversal ii. In-order traversal iii. Post-order traversal
Questions???
6) Define binary search tree. Write a function to insert an item and
recursive search algorithms for a binary search tree.
7) Write the routines for: i. Copying binary trees ii. Testing for equality of
binary trees
8) List the rules to construct the threads. Write the routines for in-order
traversal of a threaded binary tree.
9) Give in-order sequence: DJGBHEAFKIC and post-order sequence:
JGDHEBKIFCA. Construct BT for the same.
10) (a) Construct a binary tree for given expression: ((6+ (3-2)*5) ^2+3).
(b) Construct BST for the element step-by-step:
100, 85, 45, 55, 110, 20, 70, 65, 113, 145, 132, and 96.
11) For the given data, draw a binary search tree and show the array and
linked representation of the same: 100 ,85, 45, 55, 110, 20, 70, 65.
12) Construct a binary tree by using the following inorder and preorder
traversals:
inorder: BCAEDGHFI
preorder: ABCDEFGHI Department of Computer Science, RLJIT 112
Questions???
13) Consider the following tree T in (Fig. Q8(a)) write the preorder, inorder,
postorder for the tree T. Also find the depth of TREE in (Fig. Q8(a)).

14) Write recursive C function for inorder, preorder, postorder traversals of binary
tree. Also give the 3 traversals for the binary tree shown in Fig.Q7(b).

Department of Computer Science, RLJIT 113


Questions???

Department of Computer Science, RLJIT 114

You might also like