Data Structures - Lecture Notes On UNIT 3 Part 1
Data Structures - Lecture Notes On UNIT 3 Part 1
A tree is a finite set of nodes together with a finite set of directed edges (links/branches) that
define parent-child (Hierarchical) relationships.
E B
D C F H G
Tree is a non-linear data structure.
4 1 6 4 6
1 6
Tree Not a tree Not a tree
Tree Terminology:
A
B C
D E F G H
I
The level of a node x: It is the distance from the root to node x.
Generally, the root has a zero distance from itself; the root is at level 0.
The, children of the root are at level 1, their children are at level at 2, and so on.
Height of Tree: The maximum no of nodes covered in a path starting from root node to a
leaf node is called height of a tree.
A Level 0
B C Level 1
D E Level 2
F G
I Level 3
H J
Level 4
k
Binary Tree:
1 Level 0- 1node
2 3 Level 1- 2nodes
4 5 6 7 Level 2- 4nodes
10 12 13 14 15 Level 3-8nodes
8 9 11
2 3 Level 1- 2 nodes
4 5 6 7 Level 2- 4 nodes
8 9 Level 3- 2 nodes
Difference = 1
8 9
Left skewed binary tree: If the right sub tree is missing in every node of tree then we
call it as left skewed tree.
A
B
C
Right skewed binary tree: If the left sub tree is missing in every node of a tree then we
call it is right sub tree.
A4
B
C
3
Representation of a Binary Tree using Array:
Sequential Representation :
Tree nodes are stored in a linear data structure like array.
Root node is stored at index ‘0’
If a node is at a location ‘i’, then its left child is located at 2 * i + 1 and
right child is located at 2 * i + 2.
The space required by a binary tree of height h is 2h-1.
Example: Sequential representation
0
A
1 2
B D
3
5 G 6
C E
F 12
A B D C . E G . . . . . F
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
29
1. Preorder Traversal:
2. Inorder Traversal:
3. Postorder Traversal:
Example: Write the pre-order, in-order, post-order traversals for the following graph.
Preorder: A B D E H I C F J K G
Inorder: D B H E I A F K J C G
Postorder: D H I E B K J F G C A
Applications of Trees:
Trees are very important data structures in computing.
They are suitable for:
– Hierarchical structure representation, e.g.,
• File directory.
• Organizational structure of an institution.
• Class inheritance tree.
– Problem representation, e.g.,
• Expression tree.
• Decision tree.
– Efficient algorithmic solutions, e.g.,
• Search trees.
• Efficient priority queues via heaps.