You are on page 1of 24

Data Structures Using Java UNIT-III II Year IV Semester B.

Sc

TREES
A tree is a data structure in which element is attached to one (or) more
elements directly beneath it. The connections between elements are called branches.
Trees are called inverted trees because they are normally drawn with the root at the
top. Trees are used to represent hierarchical relationships between data elements.
Figure below shows the tree structure.
Level
A 1

B C D 2

E F G H I J 3

K 4

A tree consists of one (or) more nodes (or) vertices, which are connected by branches
(or) edges.
Binary Trees: Binary Tree is a data structure in which, each node consists maximum
of two child nodes. A binary tree is defined as a finite set of elements that is either
empty (or) is portioned into three disjoint subsets. The first subset contains a single
element called the root of the tree. The other two subsets are themselves binary trees,
called the left and right sub-trees of the original tree.

Fig. Below shows a binary tree Root Node Level

Right subtree 1
Left subtree A

2
C
B

F G 3

D E

I J4 4
H

Department of Computer Science 1 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

The nodes a tree are connected by branches (or) edges. Each node can have
the data and its associated information. A binary tree has a single root, called root
node, which is shown at the top of the tree. Each node except the root has exactly
one node above it, called parent. The nodes just below a node are called its children
i.e., child nodes are one level lower than the parent node.
A node which does not have any parent called root node.
A node which does not have any child is called leaf (or) terminal node.
A branch (or) edge in a tree is a link between a parent and its child.

The child nodes of same parent are said to be siblings. All nodes at a
particular level are said to be same generation.
A path in a tree is a list of distinct nodes in which successive nodes are
connected by branches in the trees. The length of a particular path is the number of
branches in that path.
The degree of a node of a tree is the number of children of that node. The
degree of leaves is zero.
The height (or) depth of a tree is the length of the largest path from the root to
leaf node. (or) the height of a tree is maximum level of any node in tree.

Ex : The height of above binary tree is 4 i.e., tree consists of 4 levels.


A subtree is a subset of tree that is itself a tree. A set of trees is referred to as forest.
A binary tree with two nodes :
If there are two nodes in the binary tree, one will be the root and other can
either be the left child of the root (or) right child of the root as shown below.
A A

and

B B
A binary tree with three nodes :
If there are three nodes in binary tree, five different binary trees can be
obtained.
A A A A
A

B B B
B

B C
C C
( i) C C
(ii) (iii) (iv) (v)

Strictly binary tree (or) Full binary tree :

Department of Computer Science 2 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

A binary tree is called a strictly binary tree if each node in a binary tree will
have either ‘0’ (or) ‘2’ children. Fig. Below shows a strictly binary tree.

B C

D E

F G

Complete binary tree : A complete binary tree can be defined as a binary tree
whose non-leaf nodes have non-empty left and right subtree and all leaf nodes are at
the same level. Fig. Below shows the complete binary tree.

B C

D E F G

Binary Search Tree (Binary Sort Tree) :


A binary search tree (BST), also called ordered binary tree, is a binary tree
such that it is an empty tree(or)

i) the data values of all the nodes in the left sub-tree are less than
that of the root.
ii) The data values of all the nodes in the right sub-tree are greater
than that of the root.
iii) The left and right sub-trees are themselves binary search trees.

Department of Computer Science 3 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Duplicate items are not allowed in a binary search tree. Fig. Below shows the binary
search tree.

20

15 35

14 17 23 40

16 26

Binary Tree Representation : Binary Trees may be represented in memory in


two ways :
a) Sequential i.e., Array Representation.
b) Linked Representation.

a) Sequential i.e., Array Representation : The simplest way to represent binary


trees in memory is the sequential representation that uses a one-dimensional
array. The following method is used to represent the tree.
i) The root of binary tree is stored in the 1st location of array.
ii) If a node is in jth location of array, then its left child is stored in the
location 2j and its right child in the location (2j+1).

The maximum size that is required for an array to store a tree is 2 d -1, where
‘d’ is the depth of the tree.
The maximum number of nodes on level i of binary tree is 2i-1
The maximum number of nodes in a binary tree of depth k is 2k -1
Ex : Consider the following binary tree.

B C

D E F G

H I J

This tree can be represented sequentially as in the following fig.

Department of Computer Science 4 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

A B C D E F G H I J

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Advantages :

1. No overhead of maintaining any pointers.


2. For a specified child, its parent node location can easily be
computed. If a child node is at jth location its parent is at location j/2.

Disadvantages :

1. The arrays are linear static data structures, thus, growing and
shrinking of a tree can not efficiently managed.
2. A number of locations are not filled and thus wastage of memory.

Linked Representation : Linked Representation of trees in memory is implemented


using pointers. Since each node in a binary tree can have maximum two children, a
node in a linked representation has two pointer fields for both left child and right
child, and one information field. If a node does not have any child, the
corresponding pointer filed is made NULL pointer. A binary tree with n nodes have
n+1 NULL pointers. Fig. Below shows a binary tree with its linked representation.

Binary Tree :
A

B C

D E F G

H I J

Linked Representation :
A

Department of Computer Science 5 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

B C

D E F G

H I J

Disadvantages :
1. Wasted space due to NULL pointers at all leaf nodes.
2. Finding a parent of a particular node is difficult.

Tree Traversals

Traversing a tree means processing it so that each node is visited exactly once.
A binary tree can be traversed in number of ways. The most common tree traversal
methods are
1. Inorder traversal
2. Preorder traversal
3. Post order traversal

Inorder traversal:

1. Traverse the left sub tree in inorder


2. Visit the root node.
3. Traverse the right sub tree in inorder

left root right

preorder traversal:

1. Visit the root node

Department of Computer Science 6 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

2. Traverse the left sub-tree in preorder


3. Traverse the right sub-tree in preorder

root left right

post order traversal:

1. Traverse the left sub-tree in post order


2. Traverse the right sub-tree in post order
3. Visit the root node

left right root

Ex: Consider the following binary tree.

B C

E F G
D

Preorder: A B D E C F G
Inorder: D B E A F C G
Postorder: D E B F G C A

Department of Computer Science 7 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Ex: Consider the following binary tree

B D

C E
G

Preorder: A B C D E F G
Inorder: C B A E F D G
Postorder: C B F E G D A

Ex:

A *

B
C
Preorder: +A*BC
Inorder: A+B*C
Postorder: ABC*+

Department of Computer Science 8 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Ex: Draw the tree whose preorder and inorder lists are
Preorder : A B D C E F
Inorder : B D A E C F

Give the post order

B C

E
F
D
Post Order : D B E F C A

Ex : The inorder and preorder traversals of a binary tree are

Inorder : D B A C E
Preorder: A B D C E
Give the post order traversal of tree.

B C

D E
Post order : D B E C A

Tree Traversal Algorithms


Following are the recursive algorithms for tree traversal.

Department of Computer Science 9 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

1. preorder traversal

preorder(T)
{
if(T==NULL) then
{
print “Tree is empty”
return
}

if(T!=NULL)
{
print Info(T)
preorder(leftptr)
preorder(rightptr)
}
}
where ‘T’ is the pointer variable contains address of root node.
leftptrleft pointer of the node
rightptrright pointer of the node.

2. Inorder Traversal

inorder(T)
{
if T=NULL then
{
print “Tree is empty”
return
}
if(T!=NULL)
{
inorder(leftptr)
print info(T)
inorder(rightptr)
}
}

3. Postorder Traversal
posrorder(T)
{
if T=NULL then

Department of Computer Science 10 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

{
print “Tree is empty”
return
}
if(T!=NULL)
{
postorder(leftptr)
postorder(rightptr)
print information(T)
}
}
Tree traversal algorithms(Non-Recursive):
Preorder:
PREORDER(INFO,LEFT,RIGHT,ROOT)
1. Initially push NULL to stack and initialize PTR (PTR is a pointer
variable contain address of node , current being scanned)
Set TOP=-1, STACK[TOP]=NULL , PTR=ROOT
2. Repeat steps 3 to 5 while PTRNULL
3. process INFO[PTR]
4. if RIGHT[PTR]NULL then
set TOP=TOP+1 and STACK[TOP]=RIGHT[PTR]
[end of if construct]
5. if LEFT[PTR]NULL then
set PTR=LEFT[PTR]
else
set PTR=STACK[TOP]
TOP=TOP-1
[end of if ]
[ end of loop]
6. exit
Inorder:
INORDER(INFO,LEFT,RIGHT,ROOT)
a. Initially push NULL to stack and initialize PTR
(PTR is a pointer variable contain address of node , current being
scanned)
Set TOP=-1 STACK[TOP]=NULL PTR=ROOT
b. repeat while PTRNULL
i. set TOP=TOP+1 and STACK[TOP]=PTR
ii. set PTR=LEFT[PTR]
[end of while loop]
c. set PTR=STACK[TOP] and TOP=TOP-1
d. repeat steps 5 to 7 while PTRNULL
e. process INFO[PTR]
f. if RIGHT[PTR]NULL then

Department of Computer Science 11 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

i. set PTR=RIGHT[PTR]
ii. GO TO step2
[end of if structure]
g. set PTR=STACK[TOP]
TOP=TOP-1
[end of while loop]
h. exit
Postorder:
POSTORDER(INFO,LEFT,RIGHT,ROOT)
a. Initially push NULL to stack and initialize PTR
(PTR is a pointer variable contain address of node , current being
scanned)
Set TOP=-1, STACK[TOP]=NULL, PTR=ROOT
b. repeat steps 3 to 5 while PTRNULL
c. set TOP=TOP+1 and STACK[TOP]=PTR
d. push right child on stack with negative mark
if RIGHT[PTR]NULL then
set TOP=TOP+1
STACK[TOP]=-RIGHT[PTR]
[end of if structure]
e. set PTR=LEFT[PTR]
[end of while loop]
f. set PTR=STACK[TOP] (pop node from stack)
TOP=TOP-1
g. if PTR is +ve
Repeat while PTR>0
a) Apply PROCESS to INFO[PTR]
b) set PTR=STACK[TOP] (POP node from stack)
TOP=TOP-1
[ end of while ]
h. if PTR is –ve
if PTR< 0 then
i. set PTR=-PTR
ii. GOTO step2
i. exit

Construction of BST

Consider the following data elements

50 40 45 60 65 58 70

1. Consider the first element as root element.

Department of Computer Science 12 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

2. Take the next element, start from root node and consider it as current node. If
the element is less than current node traverse towards left subtree, and mark
new left node as current node.
3. If the element is greater than current node traverse towards right subtree, and
mark new right node as current node.
4. Repeat the steps 2 and 3 at each node, until a leaf node is found.
5. At leaf node insert the new element
i) to left if element value is less than leaf node value
ii) to right if element value is greater than leaf node value
iii) if element is equal to leaf node value neglect the element.
Repeat the above process until tree is constructed with required no. of elements.

The tree for above example is

50

4 6
0 0

4
6
5 5 5
8

7
0

Inserting a node into a tree


To insert a node into existing tree:
1. start from the root node and consider it as current node.
2. Take the element to insert
3. Compare the element with current node value
4. If element value is less than current node value travel towards left subtree,
and mark new left node as current node.
5. If element value is greater than current node value travel towards right
subtree, and mark new right node as current node.
6. Repeat 3,4,5 until a node with one child (or) no child is found.
7. Insert the element at this node

Department of Computer Science 13 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

i) To left if node value is greater than element value


ii) To right if node value is less than element value
iii) If equal neglect the element.

Ex: Consider the following tree.

50

4 7
5 0

4 4
0 8 6
0

After inserting element ‘72’ the above tree becomes.

5
0

4
5 7
0

4 4 7
0 8 6 2
0

Deleting a node from a Tree


new element
The method to delete a node depends on the specific position of the node in
the tree.

1. To delete a leaf node :

1. Consider the leaf node to delete.


2. Start from the root node, say it as current node.
3. Compare the leaf node value with the current node value.

Department of Computer Science 14 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

4. If leaf node value is less than current node, value travel towards left
subtree of current node, and mark the new left node as current node.
5. If leaf node value is greater than current node value travel towards right
subtree of current node and mark the new right node as current node.
6. Repeat step 3 , 4 and 5 until parent node of leaf node is reached.
7. Delete leaf node and mark corresponding address pointer of parent node
as NULL.

Ex : Consider the following Tree.

7
0

5
0 8
0

4 6 9
0 0 7 0
5

If node to be deleted is ‘90’, after deletion the tree will be

7
0

5
0 8
0

4 6
0 0 7
Department of Computer Science 5 15 A.S.N. Degree College, Tenali
Data Structures Using Java UNIT-III II Year IV Semester B.Sc

2. To delete a node with one child :

If the node to be deleted has only one child, we need to adjust the link from
the parent of the deleted node to the child of the node we intend to delete.

Ex : Consider the following tree.

7
0

5
0 8
0

4 6
0 0 7
5

If node to be deleted is ‘80’. After deletion, the tree will be

7
0

6
0 7
5

5 6
0 5

Department of Computer Science 16 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

3. To delete a node with two childs :

If a node with two children has to be deleted, attach one of the subtrees
of the nodes to be deleted to the parent and then hang the other subtree onto the
appropriate node of the first subtree.

Ex: Attach right subtree to the parent node and then hang the left subtree onto a
proper node of the right subtree.
Ex: Consider the following tree
7
0

6
0 8
0

5 6 9
0 5 7 0
5

55 68

If node to be deleted is ‘65’. After deletion, tree will be

7
0

6
8
0
0

5 6 9
7
0 8 0
5

5
5
Department of Computer Science 17 A.S.N. Degree College, Tenali
Data Structures Using Java UNIT-III II Year IV Semester B.Sc

After deletion of node ‘80’, tree will be

7
0

6
0 9
0

5 6
0 8 7
5

55

Heap Tree:
Heap data structure is a specialized binary tree based data structure. Heap is a binary
tree with special characteristics. In a heap data structure, nodes are arranged based
on thier value. A heap data structure, some time called as Binary Heap.

There are two types of heap data structures and they are
1.Max Heap
2.Min Heap
Every heap data structure has the Some properties...
Property #1 (Ordering): Nodes must be arranged in a order according to values
based on Max heap or Min heap.
Property #2 (Structural): All levels in a heap must full, except last level and nodes
must be filled from left to right strictly.
Max heap is a specialized full binary tree in which every parent node contains
greater or equal value than its child nodes. And last leaf node can be alone.

Department of Computer Science 18 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Operations on Max Heap


Operations are performed on a Max heap data structure

1. Insertion
2. Deletion

1.Insertion Operation in Max Heap:


Step 1: Insert the newNode as last leaf from left to right.
Step 2: Compare newNode value with its Parent node.
Step 3: If newNode value is greater than its parent, then swap both of them.
Step 4: Repeat step 2 and step 3 until newNode value is less than its parent nede (or)
newNode reached to root.

EX:
Consider the MAX heap tree is preformed as
Step 1: Insert the newNode with value 85 as last leaf from left to right. That means
newNode is added as a right child of node with value 75. After adding max heap is
as follows...

Step 2: Compare newNode value (85) with its Parent node value (75). That means 85
> 75

Department of Computer Science 19 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Step 3: Here newNode value (85) is greater than its parent value (75),


then swap both of them. After wsapping, max heap is as follows...

Step 4: Now, again compare newNode value (85) with its parent nede value (89).

Here, newNode value (85) is smaller than its parent node value (89). So, we stop
insertion process. Finally, max heap after insetion of a new node with value 85 is as
follows...

Department of Computer Science 20 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Deletion Operation in Max Heap:


In a max heap, deleting last node is very simple as it is not disturbing max heap
properties.
Deleting root node from a max heap is title difficult as it disturbing the max heap
properties. We use the following steps to delete root node from a max heap...

Step 1: Swap the root node with last node in max heap


Step 2: Delete last node.
Step 3: Now, compare root value with its left child value.
Step 4: If root value is smaller than its left child, then compare left child with
its right sibling. Else goto Step 6
Step 5: If left child value is larger than its right sibling, then swap root with left
child. Otherwise swap root with its right child.
Step 6: If root value is larger than its left child, then compare root value with
its right childvalue.
Step 7: If root value is smaller than its right child, then swap root with rich child.
Otherwise stop the process.
Step 8: Repeat the same until root node is fixed at its exact position.

EX:
Consider the MAX heap tree is preformed as Delete root node (90) from the max
heap.

Step 1: Swap the root node (90) with last node 75 in max heap After swapping

Step 2: Delete last node. Here node with value 90. After deleting node with value 90
from heap

Department of Computer Science 21 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Step 3: Compare root node (75) with its left child (89).

Here as, root value (75) is smaller than its left child value (89). So, compare left child
(89) with its right sibling (70).

Step 4: Here, left child value (89) is larger than its right sibling (70), So, swap root
(75) with left child (89).

Step 5: Now, again compare 75 with its left child (36).

Department of Computer Science 22 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Here, node with value 75 is larger than its left child. So, we compare node with value
75 is compared with its right child 85.

Step 6: Here, node with value 75 is smaller than its right child (85). So, we swap both
of them. After swapping max heap

Step 7: Now, compare node with value 75 with its left child (15).

Department of Computer Science 23 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-III II Year IV Semester B.Sc

Here, node with value 75 is larger than its left child (15) and it does not have right
child. So we stop the process.
Finally, max heap after deleting root node (90) is as

Applications of Heap Tree:


The heap data structure has many applications.
Heapsort: One of the best sorting methods being in-place and with no quadratic
worst-case scenarios.
Selection algorithms: A heap allows access to the min or max element in constant
time, and other selections (such as median or kth-element) can be done in sub-linear
time on data that is in a heap.
Graph algorithms: By using heaps as internal traversal data structures, run time will
be reduced by polynomial order. Examples of such problems are Prim's minimal-
spanning-tree algorithm and Dijkstra's shortest-path algorithm.

Priority Queue: A priority queue is an abstract concept like "a list" or "a map"; just as
a list can be implemented with a linked list or an array, a priority queue can be
implemented with a heap or a variety of other methods.
Order statistics: The Heap data structure can be used to efficiently find the kth
smallest (or largest) element in an array.

Department of Computer Science 24 A.S.N. Degree College, Tenali

You might also like