0% found this document useful (0 votes)
13 views39 pages

Unit4 Trees

This document provides an overview of trees as non-linear data structures, detailing their hierarchical organization and terminology such as root, edge, parent, child, and leaf nodes. It explains various types of trees, including binary trees and their specific forms like strictly binary, complete, perfect, balanced, degenerate, and skewed trees, along with their properties and representation methods. Additionally, it covers binary tree traversal techniques, emphasizing the importance of these structures in data organization and manipulation.

Uploaded by

evan.mathew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views39 pages

Unit4 Trees

This document provides an overview of trees as non-linear data structures, detailing their hierarchical organization and terminology such as root, edge, parent, child, and leaf nodes. It explains various types of trees, including binary trees and their specific forms like strictly binary, complete, perfect, balanced, degenerate, and skewed trees, along with their properties and representation methods. Additionally, it covers binary tree traversal techniques, emphasizing the importance of these structures in data organization and manipulation.

Uploaded by

evan.mathew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

BCA105-2:Data Structures using C++

Unit IV

TREES: NON-LINEAR DATA STRUCTURE

A data structure is said to be linear if its elements form a sequence or a linear list. Previous
linear data structures that we have studied like an array, stacks, queues and linked lists
organize data in linear order. A data structure is said to be non linear if its elements form a
hierarchical classification where, data items appear at various levels.

Trees and Graphs are widely used non-linear data structures. Tree and graph structures
represent hierarchical relationship between individual data elements. Graphs are nothing but
trees withcertain restrictions removed.

Trees represent a special case of more general structures known as graphs. In a graph,
there is no restrictions on the number of links that can enter or leave a node, and cycles
may be present in thegraph. The figure 5.1.1 shows a tree and a non-tree.

Tree is a popular data structure used in wide range of applications. A tree data
structure can bedefined as follows...

Tree is a non-linear data structure which organizes data in hierarchical structure and
this is arecursive definition.

A tree data structure can also be defined as

follows... A tree is a finite set of one or more

nodes such that:

1
BCA105-2:Data Structures using C++

There is a specially designated node called the root. The remaining nodes are
partitioned into n>=0disjoint sets T1, ..., Tn, where each of these sets is a tree. We call
T1, ..., Tn are the subtrees of the root.

A tree is hierarchical collection of nodes. One of the nodes, known as the root, is at the top
of the hierarchy. Each node can have at most one link coming into it. The node where the
link originates iscalled the parent node. The root node has no parent. The links leaving a
node (any number of links are allowed) point to child nodes. Trees are recursive structures.
Each child node is itself the root ofa subtree. At the bottom of the tree are leaf nodes, which
have no children.

Advantages of trees

Trees are so useful and frequently used, because they have some very serious advantages:

 Trees reflect structural relationships in the data


 Trees are used to represent hierarchies
 Trees provide an efficient insertion and searching
 Trees are very flexible data, allowing to move sub trees around with minimum effort

Introduction Terminology

In a Tree, Every individual element is called as Node. Node in a tree data structure, stores
the actualdata of that particular element and link to next element in hierarchical structure.
Example

2
BCA105-2:Data Structures using C++

1. Root

In a tree data structure, the first node is called as Root Node. Every tree must have root
node. Wecan 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. In above tree, A is a
Root node

2. 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.

3. Parent

In a tree data structure, the node which is predecessor of any node is called as PARENT
NODE. Insimple 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". e.g.,
Parent (A,B,C,D).

4. 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. e.g., Children of D are (H, I,J).

5. Siblings

In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In
simplewords, the nodes with same parent are called as Sibling nodes. Ex: Siblings
(B,C, D)

6. Leaf
3
BCA105-2:Data Structures using C++

In a tree data structure, the node which does not have a child (or) node with degree zero
is calledas 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 nodewith no child. In a tree, leaf node is also called as 'Terminal' node. Ex: (K,L,F,G,M,I,J)

7. Internal Nodes

In a tree data structure, the node which has atleast one child is called as INTERNAL Node. In
simplewords, an internal node is a node with atleast one child.
In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root
node isalso said to be Internal Node if the tree has more than one node. Internal nodes are
also called as'Non-Terminal' nodes. Ex:B,C,D,E,H

8. Degree

In a tree data structure, the total number of children of a node (or)number of subtrees 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'

9. Level

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 simplewords, 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). Some authors start
root level with 1.

10. 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 thetree. In a tree, height of all leaf nodes is '0'.

11. Depth
4
BCA105-2:Data Structures using C++

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 atree is said to be depth of that tree. In a tree, depth of the root node is '0'.
12. Path

In a tree data structure, the sequence of Nodes and Edges from one node to another node is
called as PATH between that two Nodes. Length of a Path is total number of nodes in that
path. In belowexample the path A - B - E - J has length 4.

13. Sub Tree

In a tree data structure, each child from a node forms a subtree recursively. Every child
node willform a subtree on its parent node.

Tree Representations

A tree data structure can be represented in two methods. Those methods are as

follows... 1.List Representation

2. Left Child - Right Sibling

RepresentationConsider the

following tree...

5
BCA105-2:Data Structures using C++

1. 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.

The above tree example can be represented using List representation as follows...

Fig: List representation of above Tree

Fig: Possible node structure for a tree of degree k

2. 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 ofa 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...

6
BCA105-2:Data Structures using C++

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 nodeotherwise that field stores NULL.

The above tree example can be represented using Left Child - Right Sibling
representation as follows...

Consider the following tree as example

Ex.
The above example tree can be represented using List representation as follows...
7
BCA105-2:Data Structures using C++

Fig: List Representation

The above example tree can be represented using Left Child - Right Sibling representation as follows...

Fig: Left Child - Right Sibling representation

8
BCA105-2:Data Structures using C++

Binary Trees

Introduction- Binary Tree Abstract Data Type

In a normal tree, every node can have any number of children. Binary tree is a special type
of treedata structure in which every node can have a maximum of 2 children. One is known
as left childand 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 2children. Example

Definition: A binary tree is a finite set of nodes that is either empty or consists of a root
and twodisjoint binary trees called left subtree and right subtree.

ADT contains specification for the binary tree ADT.


struct node {
int data;
struct node* left;
struct node* right;
};

A binary tree has maximum two children; we can assign direct pointers to them. The declaration
of tree nodes is same as in structure to that for doubly linked lists, in that a node is a structure
including the key information plus two pointers (left and right) to other nodes.

Differences between A Tree and A Binary Tree


Differences between trees and binary trees:

TRE
E BINARY TREE

9
BCA105-2:Data Structures using C++

Each element in a tree can have any Each element in a binary tree has at most
number of subtrees. two subtrees.

The subtrees in a tree are unordered. The subtrees of each element in a binary
tree are ordered (i.e. we distinguish
between left and right subtrees).

The subtrees of a binary tree are ordered; those of a tree are not ordered.

Above two trees are different when viewed as binary trees. But same when viewed as trees.

There are different types of binary trees and they are...


1. Strictly Binary Tree (or) Full Binary Tree

In a binary tree, every node can have a maximum of two children. But in strictly binary tree,
everynode should have exactly two children or none. That means every internal node must
have exactlytwo 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
BinaryTree. Strictly binary tree is also called as Full Binary Tree or Proper Binary Tree or 2-
Tree

2. Complete Binary Tree

Complete Binary Tree has all levels completely filled with nodes except the last level and in

the last level, all the nodes are as left side as possible.

10
BCA105-2:Data Structures using C++

Valid and Invalid Structure of Complete Binary Tree

3. Perfect Binary Tree

Perfect Binary Tree is a Binary Tree in which all internal nodes have 2 children and all the leaf nodes

are at the same depth or same level.

Valid and Invalid Structure of Perfect Binary Tree

11
BCA105-2:Data Structures using C++

4. Balanced Binary Tree


A balanced binary tree or height-balanced binary tree is such a tree whose left and right subtrees'
heights differ by not more than 1, which means the height difference could be -1, 0, and 1. A
balanced binary tree is also known as a height-balanced tree.
Necessary conditions for a balanced binary tree:
 The height difference should not be more than 1.
 The Left sub-tree should be balanced.
 The right sub-tree should be balanced.
The height difference of a tree is calculated as |Left subtree| – |Right subtree| or |Right subtree| – |Left
subtree|. The difference should not be more than 1.
Example of Balanced Binary Tree

12
BCA105-2:Data Structures using C++

5. Degenerate(or Pathological) Binary Tree

Degenerate Binary Tree is a Binary Tree where every parent node has only one child node.

Valid and Invalid Structure of Degenerate Binary Tree|

6. Skewed Binary Tree


A 'Skewed Binary Tree' is a 'Degenerate Binary Tree' in which the tree can have only one
child.

13
BCA105-2:Data Structures using C++

There are 2 special types of skewed tree:


1. Left Skewed Binary Tree:
These are those skewed binary trees in which all the nodes are having a left child or no child
at all. It is a left side dominated tree. All the right children remain as null.

2. Right Skewed Binary Tree:

These are those skewed binary trees in which all the nodes are having a right child or no child
at all. It is a right side dominated tree. All the left children remain as null.

14
BCA105-2:Data Structures using C++

Properties Of Binary Trees

 A binary tree of n elements has n-1 edges


 The minimum number of nodes in a binary tree of height H is H + 1
 The maximum number of nodes in a binary tree of height H is 2H+1 – 1
 Total Number of leaf nodes in a Binary Tree = Total Number of nodes with
two children + 1
 If h = height of a binary tree, then
a. Maximum number of leaves = 2h
 If a binary tree contains m nodes at level l, it contains at most 2m nodes at
level l + 1.

Binary Tree Representation

A binary tree data structure is represented using two methods. Those methods are
Array Representation

1. Linked List Representation

Consider the following binary tree...

1. Array Representation of Binary Tree


In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent a binary tree.
Consider the above example of a binary tree and it is represented as follows...

15
BCA105-2:Data Structures using C++

To represent a binary tree of depth 'n' using array representation, we need one dimensional array with a
maximum size of 2n + 1.

2. Linked List Representation of Binary Tree


We use a 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.
In this linked list representation, a node has the following structure...

The above example of the binary tree represented using Linked list representation is shown as follows...

The below is an implementation of Binary trees

16
BCA105-2:Data Structures using C++

17
BCA105-2:Data Structures using C++

Binary Tree Traversal Techniques:

A tree traversal is a method of visiting every node in the tree. By visit, we mean that some
type of operation is performed. For example, you may wish to print the contents of the nodes.

There are four common ways to traverse a binary tree:

1. Preorder
2. Inorder
3. Postorder
4. Level order

In the first three traversal methods, the left subtree of a node is traversed before the right
subtree. The difference among them comes from the difference in the time at which a root
node is visited.

Tree Traversal Algorithms:

Inorder Traversal:

In the case of inorder traversal, the root of each subtree is visited after its left subtree has been
traversed but before the traversal of its right subtree begins. The steps for traversing a binary
tree in inorder traversal are:

1. Visit the left subtree, using inorder.


2. Visit the root.
3. Visit the right subtree, using inorder.

The algorithm for inorder traversal is as follows:

void inorder(node *root)


{
if(root != NULL)
{
inorder(root->lchild);
print root -> data;
inorder(root->rchild);
}
}

Preorder Traversal:

In a preorder traversal, each root node is visited before its left and right subtrees are traversed.
Preorder search is also called backtracking. The steps for traversing a binary tree in preorder
traversal are:

1. Visit the root. 18


2. Visit the left subtree, using preorder.
3. Visit the right subtree, using preorder.
BCA105-2:Data Structures using C++

The algorithm for preorder traversal is as follows:

void preorder(node *root)


{
if( root != NULL )
{
print root -> data;
preorder (root -> lchild);
preorder (root -> rchild);
}
}

Postorder Traversal:

In a postorder traversal, each root is visited after its left and right subtrees have beentraversed.
The steps for traversing a binary tree in postorder traversal are:

1. Visit the left subtree, using postorder.


2. Visit the right subtree, using postorder
3. Visit the root.

The algorithm for postorder traversal is as follows:

void postorder(node *root)


{
if( root != NULL )
{
postorder (root -> lchild);
postorder (root -> rchild);
print (root -> data);
}
}

Level order Traversal:

In a level order traversal, the nodes are visited level by level starting from the root, and going
from left to right. The level order traversal requires a queue data structure. So, it is not
possible to develop a recursive procedure to traverse the binary tree in level order. This is
nothing but a breadth first search technique.

19
BCA105-2:Data Structures using C++

The algorithm for level order traversal is as follows:

void levelorder()
{
int j;
for(j = 0; j < ctr; j++)
{
if(tree[j] != NULL)
print tree[j] -> data;
}
}

Example 1:

Traverse the following binary tree in pre, post, inorder and level order.

A Preo rder traversal yields:


A,B, D, C , E, G , F , H, I
B C
Posto rder traversal yields:
D E F D,B, G , E, H, I, F , C , A

Ino rder traversal yields:


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

Level o rder traversal yields:


A,B, C , D, E, F , G , H, I
Bina ry T re e
Pre, P o st, Inorder a nd lev e l order T rav
ers ing

Example 2:

Traverse the following binary tree in pre, post, inorder and level order.

Preo rder traversal yields:


P, F , B, H, G , S, R, Y, T, W, Z

Posto rder traversal yields:


B H R Y B, G , H, F , R, W, T, Z, Y, S, P

Ino rder traversal yields:


B, F , G , H, P, R, S, T, W, Y, Z

Level o rder traversal yields: P, F ,S, B, H,


R, Y, G , T, Z, W
20

Bina ry T re e Pre, P o st, Inorder a nd lev e l order T rav ers ing


BCA105-2:Data Structures using C++

Example 3:

Traverse the following binary tree in pre, post, inorder and level order.

Preo rder traversal yields:


2, 7 , 2 , 6 , 5 , 11 , 5 , 9 , 4

Posto rder travarsal yields: 2, 5 , 11


, 6, 7,4,9,5, 2
2 6
Ino rder travarsal yields:
2, 7 , 5 , 6 , 11 , 2 , 5 , 4 , 9
5 11
Level o rder traversal yields:2, 7 , 5
, 2 , 6 , 9 , 5 , 11 , 4

Pre, P o st, Inorder a nd lev e l order T rav ers ing

Example 4:

Traverse the following binary tree in pre, post, inorder and level order.

Preo rder traversal yields: A, B,D, G ,


K, H, L, M , C , E

Posto rder travarsal yields: K,G , L, M


, H, D, B, E, C , A

Ino rder travarsal yields: K, G ,D, L, H,


M , B, A, E, C

Level o rder traversal yields: A, B, C ,


D, E, G , H, K, L, M

Bina ry T re e Pre, P o st, Inorder a nd lev e l order T rav ers ing

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 21
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.


BCA105-2:Data Structures using C++

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 the left and right sub trees:

Left sub tree is: D G B Right

sub tree is: H E I C F

The Binary tree upto this point looks like:

DGB HEICF

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:

HEICF

DG

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 22
right of D.
BCA105-2:Data Structures using C++

The Binary tree upto this point looks like:

HEICF

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:

D
HEI

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 theright
of E.

The Binary tree upto this point looks like:

Example 2:

Construct a binary tree from a given postorder and inorder sequence:


Inorder: D G B A H E I C F 23
Postorder: G D B H I E F C A
BCA105-2:Data Structures using C++

Solution:

From Postorder sequence G D B H I E F C A, the root is: A

From Inorder sequence D G B A H E I C F, we get the left and right sub trees:

Left sub tree is: D G B Right


sub tree is: H E I C F

The Binary tree upto this point looks like:

DGB HEICF

To find the root, left and right sub trees for D G B:

From the postorder sequence G D B, the root of tree is: B

From the inorder sequence D G B, we can find that D G are to the left of B and there isno
right subtree for B.

The Binary tree upto this point looks like:

HEICF

DG

To find the root, left and right sub trees for D G:

From the postorder sequence G D, the root of the tree is: D

From the inorder sequence D G, we can find that is no left subtree for D and G is to the right
of D.

The Binary tree upto this point looks like:

HEICF

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


24
From the postorder sequence H I E F C, 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 to the left of C and F isthe
BCA105-2:Data Structures using C++

right subtree for C.The Binary tree upto this point looks like:

HEI

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

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

From the inorder sequence H E I, we can find that H is left subtree for E and I is to theright
of E.

The Binary tree upto this point looks like:

Example 3:

Construct a binary tree from a given preorder and inorder sequence:

Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Preorder: n6 n2 n1 n4 n3 n5 n9 n7 n8

Solution:

From Preorder sequence n6 n2 n1 n4 n3 n5 n9 n7 n8, the root is: n6

From Inorder sequence n1 n2 n3 n4 n5 n6 n7 n8 n9, we get the left and right subtrees:

Left sub tree is: n1 n2 n3 n4 n5

Right sub tree is: n7 n8 n9

The Binary tree upto this point looks like:


n6

25
n1 n2 n3 n4 n5 n7 n8 n9
BCA105-2:Data Structures using C++

To find the root, left and right sub trees for n1 n2 n3 n4 n5:

From the preorder sequence n2 n1 n4 n3 n5, the root of tree is: n2

From the inorder sequence n1 n2 n3 n4 n5, we can find that n1 is to the left of n2 and n3 n4
n5 are to the right of n2. The Binary tree upto this point looks like:
n6

n2 n7 n8 n9

n1 n3 n4 n5

To find the root, left and right sub trees for n3 n4 n5:

From the preorder sequence n4 n3 n5, the root of the tree is: n4

From the inorder sequence n3 n4 n5, we can find that n3 is to the left of n4 and n5 isat the
right of n4.

The Binary tree upto this point looks like:


n6

n2 n7 n8 n9

n1 n4

n3 n5

To find the root, left and right sub trees for n7 n8 n9:

From the preorder sequence n9 n7 n8, the root of the left sub tree is: n9

From the inorder sequence n7 n8 n9, we can find that n7 and n8 are at the left of n9and no
right subtree of n9.

The Binary tree upto this point looks like:


n6

n9
n2

n1 n4 n7 n8

n3 n5

26
To find the root, left and right sub trees for n7 n8:

From the preorder sequence n7 n8, the root of the tree is: n7
BCA105-2:Data Structures using C++

From the inorder sequence n7 n8, we can find that is no left subtree for n7 and n8 is at the right of n7.

The Binary tree upto this point looks like:


n6

n2 n9

n1 n4 n7

n3 n5 n8

Example 4:

Construct a binary tree from a given postorder and inorder sequence: Inorder: n1 n2

n3 n4 n5 n6 n7 n8 n9
Postorder: n1 n3 n5 n4 n2 n8 n7 n9 n6

Solution:

From Postorder sequence n1 n3 n5 n4 n2 n8 n7 n9 n6, the root is: n6

From Inorder sequence n1 n2 n3 n4 n5 n6 n7 n8 n9, we get the left and right subtrees:

Left sub tree is: n1 n2 n3 n4 n5Right sub


tree is: n7 n8 n9

The Binary tree upto this point looks like:

n6

n1 n2 n3 n4 n5

To find the root, left and right sub trees for n1 n2 n3 n4 n5:

From the postorder sequence n1 n3 n5 n4 n2, the root of tree is: n2

From the inorder sequence n1 n2 n3 n4 n5, we can find that n1 is to the left of n2 and n3 n4 n5 are to
the right of n2.

The Binary tree upto this point looks like:

27
BCA105-2:Data Structures using C++

n6

n2

n1

To find the root, left and right sub trees for n3 n4 n5:

From the postorder sequence n3 n5 n4, the root of the tree is: n4

From the inorder sequence n3 n4 n5, we can find that n3 is to the left of n4 and n5 isto the right of
n4. The Binary tree upto this point looks like:

n6

n2 n7 n8 n9

n1 n4

n3 n5

To find the root, left and right sub trees for n7 n8 and n9:

From the postorder sequence n8 n7 n9, the root of the left sub tree is: n9

From the inorder sequence n7 n8 n9, we can find that n7 and n8 are to the left of n9and no right
subtree for n9.

The Binary tree upto this point looks like:

n6

n2 n9

n1 n4 n7 n8

n3 n5

To find the root, left and right sub trees for n7 and n8:

28
BCA105-2:Data Structures using C++

From the postorder sequence n8 n7, the root of the tree is: n7

From the inorder sequence n7 n8, we can find that there is no left subtree for n7 and n8 is to the
right of n7. The Binary tree upto this point looks like:

n6

n2 n9

n1 n4 n7

n3 n5 n8

Example

Question : we have the following list J, R, D, G, T, E, M, H, P, A, F, Q which is inserted in order in an


empty binary tree.
This is the inorder traversal :

A, D, E, F, G, H, J, M, P, Q, R, T
construct the binary tree.

The answer is :

29
BCA105-2:Data Structures using C++

Binary Search Trees

A binary search tree is a binary tree. It may be empty. If it is not empty then itsatisfies 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.

Figur (a) is a binary search tree, whereas figure(b) is not a binary searchtree.

16 16

12 20 12 20

11 14 19 11 14 197

13 13 17

Not a Binary Search Tree


(b)

trees

30
BCA105-2:Data Structures using C++

left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

Fig: Example Binary Search Trees

AVL Tree Data structure

AVL tree is a height-balanced binary search tree. That means, an AVL tree is also a binary
search tree but it is a balanced tree. A binary tree is said to be balanced if, the difference
between the heights of left and right subtrees of every node in the tree is either -1, 0 or
+1. In other words, a binary tree is said to be balanced if the height of left and right children
of every node differ by either -1, 0 or +1. In an AVL tree, every node maintainsextra
information known as balance factor. The AVL tree was introduced in the year 1962 by
G.M. Adelson-Velsky and E.M. Landis.

An AVL tree is defined as follows...

An AVL tree is a balanced binary search tree. In an AVL tree, balance factor ofevery node
is either -1, 0 or +1.

Balance factor of a node is the difference between the heights of the left and right subtrees
of that node. The balance factor of a node is calculated either height of leftsubtree -
height of right subtree (OR) height of right subtree - height of left subtree. In the
following explanation, we calculate as follows...

Balance factor = height Of LeftSubtree height Of RightSubtree

Example of AVL Tree

31
BCA105-2:Data Structures using C++

The above tree is a binary search tree and every node is satisfying balance factorcondition. So this tree
is said to be an AVL tree.

Every AVL Tree is a binary search tree but every Binary Search Tree need not beAVL tree.

Binary Search Tree Operations-

Commonly performed operations on binary search tree are-

1. Search Operation
2. Insertion Operation
3. Deletion Operation

1. Search Operation-

Search Operation is performed to search a particular element in the Binary Search Tree.

Rules-

For searching a given key in the BST,


 Compare the key with the value of root node.
 If the key is present at the root node, then return the root node.
 If the key is greater than the root node value, then recur for the root node’s right subtree.
 If the key is smaller than the root node value, then recur for the root node’s left subtree.

Example-

32
BCA105-2:Data Structures using C++

Consider key = 45 has to be searched in the given BST-

 We start our search from the root node 25.

 As 45 > 25, so we search in 25’s right subtree.


 As 45 < 50, so we search in 50’s left subtree.
 As 45 > 35, so we search in 35’s right subtree.
 As 45 > 44, so we search in 44’s right subtree but 44 has no subtrees.
 So, we conclude that 45 is not present in the above BST.

2. Insertion Operation-

Insertion Operation is performed to insert an element in the Binary Search Tree.

33
BCA105-2:Data Structures using C++

Rules-

The insertion of a new key always takes place as the child of some leaf node.
For finding out the suitable leaf node,
 Search the key to be inserted from the root node till some leaf node is reached.
 Once a leaf node is reached, insert the key as child of that leaf node.

Example-

Consider the following example where key = 40 is inserted in the given BST-

 We start searching for value 40 from the root node 100.


 As 40 < 100, so we search in 100’s left subtree.
 As 40 > 20, so we search in 20’s right subtree.
 As 40 > 30, so we add 40 to 30’s right subtree.

Example: Creation of tree

34
BCA105-2:Data Structures using C++

3. Deletion Operation-

Deletion Operation is performed to delete a particular element from the Binary Search Tree.

When it comes to deleting a node from the binary search tree, following three cases are possible-

35
BCA105-2:Data Structures using C++

Case-01: Deletion Of A Node Having No Child (Leaf Node)-

Just remove / disconnect the leaf node that is to deleted from the tree.

Example-

Consider the following example where node with value = 20 is deleted from the BST-

Case-02: Deletion Of A Node Having Only One Child-

Just make the child of the deleting node, the child of its grandparent.

Example-

Consider the following example where node with value = 30 is deleted from the BST-

36
BCA105-2:Data Structures using C++

Case-02: Deletion Of A Node Having Two Children-

A node with two children may be deleted from the BST in the following two ways-

Method-01:

 Visit to the right subtree of the deleting node.


 Pluck the least value element called as inorder successor.
 Replace the deleting element with its inorder successor.

Example-

Consider the following example where node with value = 15 is deleted from the BST-

37
BCA105-2:Data Structures using C++

Method-02:

 Visit to the left subtree of the deleting node.


 Pluck the greatest value element called as inorder predecessor.
 Replace the deleting element with its inorder predecessor.

Example-

Consider the following example where node with value = 15 is deleted from the BST-

The complexity of the Binary Search tree

Let's see the time and space complexity of the Binary search tree. We will see the time complexity for insertion,
deletion, and searching operations in best case, average case, and worst case.

1. Time Complexity
Operations Best case time Average case Worst case time
complexity time complexity
complexity

Insertion O(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)

Search O(log n) O(log n) O(n)

Where 'n' is the number of nodes in the given tree.

38
BCA105-2:Data Structures using C++

2. Space Complexity
Operations Space complexity

Insertion O(n)

Deletion O(n)

Search O(n)

o The space complexity of all operations of Binary search tree is O(n).

39

You might also like