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

Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

The document provides an overview of tree data structures, including their hierarchical organization, basic terminologies, types, operations, and traversal techniques. It explains the significance of trees in representing hierarchical data, their applications in various fields, and the advantages and disadvantages of using tree structures. Additionally, it details different traversal methods such as inorder, preorder, and postorder, along with their respective algorithms and implementations.

Uploaded by

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

Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

The document provides an overview of tree data structures, including their hierarchical organization, basic terminologies, types, operations, and traversal techniques. It explains the significance of trees in representing hierarchical data, their applications in various fields, and the advantages and disadvantages of using tree structures. Additionally, it details different traversal methods such as inorder, preorder, and postorder, along with their respective algorithms and implementations.

Uploaded by

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

Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Classifying in hierarchy levels

Tree data structure

A tree data structure is a hierarchical structure that is used to represent and organize
data in a way that is easy to navigate and search. It is a collection of nodes that are
connected by edges and has a hierarchical relationship between the nodes.

The topmost node of the tree is called the root, and the nodes below it are called the child
nodes. Each node can have multiple child nodes, and these child nodes can also have their
own child nodes, forming a recursive structure.
This data structure is a specialized method to organize and store data in the computer to
be used more effectively. It consists of a central node, structural nodes, and sub-nodes,

1
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

which are connected via edges. We can also say that tree data structure has roots,
branches, and leaves connected with one another.

2
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Basic Terminologies In Tree Data Structure:

 Parent Node: The node which is a predecessor of a node is called the parent node of
that node. {B} is the parent node of {D, E}.
 Child Node: The node which is the immediate successor of a node is called the child
node of that node. Examples: {D, E} are the child nodes of {B}.
 Root Node: The topmost node of a tree or the node which does not have any parent
node is called the root node. {A} is the root node of the tree. A non-empty tree must
contain exactly one root node and exactly one path from the root to all other nodes of
the tree.
 Leaf Node or External Node: The nodes which do not have any child nodes are called
leaf nodes. {K, L, M, N, O, P, G} are the leaf nodes of the tree.
 Ancestor of a Node: Any predecessor nodes on the path of the root to that node are
called Ancestors of that node. {A,B} are the ancestor nodes of the node {E}
 Descendant: Any successor node on the path from the leaf node to that node. {E,I} are
the descendants of the node {B}.
 Sibling: Children of the same parent node are called siblings. {D,E} are called siblings.
 Level of a node: The count of edges on the path from the root node to that node. The
root node has level 0.
 Internal node: A node with at least one child is called Internal Node.

3
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

 Neighbour of a Node: Parent or child nodes of that node are called neighbors of that
node.
 Subtree: Any node of the tree along with its descendant.
 Depth. In a tree, many edges from the root node to the particular node are called the
depth of the tree. In the tree, the total number of edges from the root node to the leaf
node in the longest path is known as "Depth of Tree". In the tree data structures, the
depth of the root node is 0.

Representation of Tree Data Structure:

A tree consists of a root, and zero or more subtrees T1, T2, … , Tk such that there is an
edge from the root of the tree to the root of each subtree.

Representation of Tree Data Structure


4
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Representation of a Node in Tree Data Structure:


struct Node
{
int data;
struct Node *first_child;
struct Node *second_child;
struct Node *third_child;
.
.
.
struct Node *nth_child;
};
Example of Tree data structure

Here,
 Node 1 is the root node

5
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

 1 is the parent of 2 and 3


 2 and 3 are the siblings
 4, 5, 6, and 7 are the leaf nodes
 1 and 2 are the ancestors of 5

Types of Tree data structures:

 Binary tree: In a binary tree, each node can have a maximum of two children linked to
it. Some common types of binary trees include full binary trees, complete binary trees,
balanced binary trees, and degenerate or pathological binary trees.
 Ternary Tree: A Ternary Tree is a tree data structure in which each node has at most
three child nodes, usually distinguished as “left”, “mid” and “right”.

6
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

 N-ary Tree or Generic Tree: Generic trees are a collection of nodes where each node is
a data structure that consists of records and a list of references to its children(duplicate
references are not allowed). Unlike the linked list, each node stores the address of
multiple nodes.

Basic Operation Of Tree Data Structure:


 Create – create a tree in the data structure.

 Insert − Inserts data in a tree.

 Search − Searches specific data in a tree to check whether it is present or not.

 Traversal:

 Preorder Traversal – perform Traveling a tree in a pre-order manner in the

data structure.
 In order Traversal – perform Traveling a tree in an in-order manner.

 Post-order Traversal –perform Traveling a tree in a post-order manner.

Why Tree is considered a non-linear data structure?


The data in a tree are not stored in a sequential manner i.e., they are not stored linearly.
Instead, they are arranged on multiple levels or we can say it is a hierarchical structure.
For this reason, the tree is considered to be a non-linear data structure.

7
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Properties of Tree Data Structure:


 Number of edges: An edge can be defined as the connection between two nodes. If a

tree has N nodes then it will have (N-1) edges. There is only one path from each node to
any other node of the tree.
 Depth of a node: The depth of a node is defined as the length of the path from the root

to that node. Each edge adds 1 unit of length to the path. So, it can also be defined as
the number of edges in the path from the root of the tree to the node.
 Height of a node: The height of a node can be defined as the length of the longest path

from the node to a leaf node of the tree.


 Height of the Tree: The height of a tree is the length of the longest path from the root

of the tree to a leaf node of the tree.


 Degree of a Node: The total count of subtrees attached to that node is called the degree

of the node. The degree of a leaf node must be 0. The degree of a tree is the maximum
degree of a node among all the nodes in the tree.

8
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Need for Tree Data Structure


1. One reason to use trees might be because you want to store information that naturally
forms a hierarchy. For example, the file system on a computer:

File System

2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than
Linked List and slower than arrays).
3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than
Unordered Linked Lists).
4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on the number of
nodes as nodes are linked using pointers.
9
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Application of Tree Data Structure:


 File System: This allows for efficient navigation and organization of files.

 Data Compression: Huffman coding is a popular technique for data compression that

involves constructing a binary tree where the leaves represent characters and their
frequency of occurrence. The resulting tree is used to encode the data in a way that
minimizes the amount of storage required.
 Compiler Design: In compiler design, a syntax tree is used to represent the structure of

a program.
 Database Indexing: B-trees and other tree structures are used in database indexing to

efficiently search for and retrieve data.

Other Applications of Tree Data Structure:


1. Store hierarchical data, like folder structure, organization structure, XML /HTML
data.
2. Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It
also allows finding closest item
3. Heap is a tree data structure which is implemented using arrays and used to implement
priority queues.
4. B-Tree and B+ Tree : They are used to implement indexing in databases.
5. Syntax Tree: Scanning, parsing , generation of code and evaluation of arithmetic
expressions in Compiler design.

10
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

6. K-D Tree: A space partitioning tree used to organize points in K dimensional space.
7. Trie : Used to implement dictionaries with prefix lookup.
8. Suffix Tree : For quick pattern searching in a fixed text.
9. Spanning Trees and shortest path trees are used in routers and bridges respectively in
computer networks
10. As a workflow for compositing digital images for visual effects.
11. Decision trees.
12. Organization chart of a large organization.
13. In XML parser.
14. Machine learning algorithm.
15. For indexing in database.
16. IN server like DNS (Domain Name Server)
17. In Computer Graphics.
18. To evaluate an expression.
19. In chess game to store defense moves of player.
20. In java virtual machine.
21. Tree data structures are used to organize and manage files and directories in a file
system. Each file and directory is represented as a node in the tree, with parent-child
relationships indicating the hierarchical structure of the file system.
22. Tree data structures are often used in parsing, such as in compilers and interpreters,
to represent the structure of a program or a document.

11
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

23. Tree data structures, such as binary search trees, are commonly used to implement
efficient searching and sorting algorithms.
24. Graphics and UI design
25. Tree data structures are commonly used in decision-making algorithms in artificial
intelligence, such as game-playing algorithms, expert systems, and decision trees.
26. Tree data structures can be used to represent the topology of a network and to
calculate routing tables for efficient data transmission.

Advantages of Tree Data Structure:


 Tree offer Efficient Searching Depending on the type of tree, with average search times

of O(log n) for balanced trees like AVL.


 Trees provide a hierarchical representation of data, making it easy to organize and

navigate large amounts of information.


 The recursive nature of trees makes them easy to traverse and manipulate using

recursive algorithms.
Disadvantages of Tree Data Structure:
 Unbalanced Trees, meaning that the height of the tree is skewed towards one side,

which can lead to inefficient search times.


 Trees demand more memory space requirements than some other data structures like

arrays and linked lists, especially if the tree is very large.

12
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

 The implementation and manipulation of trees can be complex and require a good
understanding of the algorithms.

Tree Traversal Techniques


Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only
one logical way to traverse them, trees can be traversed in different ways.
A Tree Data Structure can be traversed in following ways:
1. Depth First Search or DFS
1. Inorder Traversal
2. Preorder Traversal
3. Postorder Traversal
2. Level Order Traversal or Breadth First Search or BFS
3. Boundary Traversal
4. Diagonal Traversal

13
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Tree Traversal

14
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Inorder Traversal:
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left->subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right->subtree)

Uses of Inorder Traversal:

In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing
order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where
Inorder traversal is reversed can be used.
Code implementation of Inorder traversal. (Exp.4.a)

// C program for inorder tree traversals

#include <stdio.h>

15
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

#include <stdlib.h>

// A binary tree node has data, pointer to left child

// and a pointer to right child

struct node {

int data;

struct node* left;

struct node* right;

};

16
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// Helper function that allocates a new node with the

// given data and NULL left and right pointers.

struct node* newNode(int data)

struct node* node

= (struct node*)malloc(sizeof(struct node));

node->data = data;

node->left = NULL;

node->right = NULL;

17
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

return (node);

// Given a binary tree, print its nodes in inorder

void printInorder(struct node* node)

if (node == NULL)

return;

18
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// First recur on left child

printInorder(node->left);

// Then print the data of node

printf("%d ", node->data);

// Now recur on right child

printInorder(node->right);

19
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// Driver code

int main()

struct node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

20
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// Function call

printf("Inorder traversal of binary tree is \n");

printInorder(root);

getchar();

return 0;

Output
Inorder traversal of binary tree is
42513

21
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Time Complexity: O(N)


Auxiliary Space: If we don’t consider the size of the stack for function calls then O(1)
otherwise O(h) where h is the height of the tree.

Preorder Traversal:
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left->subtree)
3. Traverse the right subtree, i.e., call Preorder(right->subtree)

Uses of Preorder : (Ex.4.b)

Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get
prefix expressions on an expression tree.
Code implementation of Preorder traversal:

#include <stdio.h>
22
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

#include <stdlib.h>

// A binary tree node has data, pointer to left child

// and a pointer to right child

struct node {

int data;

struct node* left;

struct node* right;

};

23
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// Helper function that allocates a new node with the

// given data and NULL left and right pointers.

struct node* newNode(int data)

struct node* node

= (struct node*)malloc(sizeof(struct node));

node->data = data;

node->left = NULL;

24
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

node->right = NULL;

return (node);

// Given a binary tree, print its nodes in preorder

void printPreorder(struct node* node)

if (node == NULL)

return;

25
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// First print data of node

printf("%d ", node->data);

// Then recur on left subtree

printPreorder(node->left);

// Now recur on right subtree

printPreorder(node->right);

26
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// Driver code

int main()

struct node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

27
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// Function call

printf("Preorder traversal of binary tree is \n");

printPreorder(root);

getchar();

return 0;

Output
Preorder traversal of binary tree is
12453

28
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Postorder Traversal:

Algorithm Postorder (tree)


1. Traverse the left subtree, i.e., call Postorder(left->subtree)
2. Traverse the right subtree, i.e., call Postorder(right->subtree)
3. Visit the root

Uses of Postorder: (Exp.4.c)

Postorder traversal is used to delete the tree. Please see the question for the deletion of a
tree for details. Postorder traversal is also useful to get the postfix expression of an
expression tree

29
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

//C program for postorder tree traversals

#include <stdio.h>

#include <stdlib.h>

// A binary tree node has data, pointer to left child

// and a pointer to right child

struct node {

int data;

struct node* left;

30
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

struct node* right;

};

// Helper function that allocates a new node with the

// given data and NULL left and right pointers.

struct node* newNode(int data)

struct node* node

= (struct node*)malloc(sizeof(struct node));

31
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

node->data = data;

node->left = NULL;

node->right = NULL;

return (node);

// Given a binary tree, print its nodes according to the

// "bottom-up" postorder traversal.

void printPostorder(struct node* node)

32
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

if (node == NULL)

return;

// First recur on left subtree

printPostorder(node->left);

// Then recur on right subtree

printPostorder(node->right);

33
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

// Now deal with the node

printf("%d ", node->data);

// Driver code

int main()

struct node* root = newNode(1);

root->left = newNode(2);

34
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

// Function call

printf("Postorder traversal of binary tree is \n");

printPostorder(root);

getchar();

return 0;

35
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Output
Postorder traversal of binary tree is
45231
Some other Tree Traversals Techniques:
Some of the other tree traversals are:

Level Order Treversal


For each node, first, the node is visited and then it’s child nodes are put in a FIFO queue.
Then again the first node is popped out and then it’s child nodes are put in a FIFO queue
and repeat until queue becomes empty.
Example:
Input:

36
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Level Order Treversal:


1
23
45

Boundary Traversal
The Boundary Traversal of a Tree includes:
1. left boundary (nodes on left excluding leaf nodes)
2. leaves (consist of only the leaf nodes)
3. right boundary (nodes on right excluding leaf nodes)

37
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Diagonal Traversal
In the Diagonal Traversal of a Tree, all the nodes in a single diagonal will be printed one
by one.
Input :

38
Unit III – Topic 1 – TREE ADT & TREE TRAVERSAL

Diagonal Traversal of binary tree:


8 10 14
3 6 7 13
14

39

You might also like