DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree

The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the maximum number of nodes will be the width of the binary tree.

Algorithm to Find the Maximum Width of a Tree

In the given tree,

Level 1 has one node.

Level 2 has two nodes.

Level 3 has three nodes.

Hence the maximum width of the tree is 3.

To do this, we have two methods:

Approach 1

In this approach, we will calculate the height of the tree. Using the height, we will go to each level and count the total number of nodes. Each time the nodes are calculated, they will be updated with the current maximum width.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // Create the tree structure
 class Node {
 public:
     int data; // value of a Node
     Node *left, *right; // The left and right pointers to the Node
 };
 // Function to insert a new node
 Node* newnode(int data)
 {
     Node* root = new Node(); // create root Node
     root->data = data; // insert the value
     root->left = root->right = NULL; // the left and right child are null currently
     return root;
 }
 // Function to find the height of the tree
 int Height(Node* root)
 {
     // if root is NULL
     if (root == NULL)
         return 0;
     else {
         // Calculate height of left subtree
         int l_height = Height(root->left);
         // Calculate height of the right subtree
         int r_height = Height(root->right);
         return l_height > r_height ? l_height + 1 : r_height + 1;
     }
 }
 // Function to find nodes at given level
 int findWidth(Node* root, int level)
 {
     if (root == NULL)
         return 0;
     if (level == 1)
         return 1;
     // find for left and right
     return findWidth(root->left, level - 1) + findWidth(root->right, level - 1);
 }
 // Function to find the maximum width
 int max_width(Node* root)
 {
     int maxwidth = 0; // Initialise max width as zero
     int height = Height(root); // Calculate the Height of the tree
     // for each level find the maximum width
     for (int i = 1; i <= height; i++) {
         int width = findWidth(root, i); // find width at ith level
         maxwidth = max(maxwidth, width); // update maxwidth
     }
     return maxwidth;
 }
 int main() // Main function
 {
     Node* root = newnode(1); // declare root node
     root->left = newnode(2); // Left child of root
     root->right = newnode(3); // Right child of root
     root->left->left = newnode(4); // Left child of left parent
     root->right->left = newnode(5); // Left child of right parent
     root->right->right = newnode(6); // Right child of right parent
     cout << "The maximum width of the tree is " << max_width(root);
     return 0;
 } 

C code:

 #include <stdlib.h>
 #include <stdio.h>
 // Create the tree structure
 struct Node {
     int data; // value of a Node
     struct Node *left, *right; // The left and right pointers to the Node
 };
 // Function to insert a new node
 struct Node* newnode(int data)
 {
     struct Node* root = (struct Node*)(malloc(sizeof(struct Node))); // create root Node
     root->data = data; // insert the value
     root->left = root->right = NULL; // the left and right child are null currently
     return root;
 }
 // Function to find the height of the tree
 int Height(struct Node* root)
 {
     // if root is NULL
     if (root == NULL)
         return 0;
     else {
         // Calculate height of left subtree
         int l_height = Height(root->left);
         // Calculate height of the right subtree
         int r_height = Height(root->right);
         return l_height > r_height ? l_height + 1 : r_height + 1;
     }
 }
 // Function to find nodes at given level
 int findWidth(struct Node* root, int level)
 {
     if (root == NULL)
         return 0;
     if (level == 1)
         return 1;
     // find for left and right
     return findWidth(root->left, level - 1) + findWidth(root->right, level - 1);
 }
 // Function to find the maximum width
 int max_width(struct Node* root)
 {
     int maxwidth = 0; // Initialise max width as zero
     int height = Height(root); // Calculate the Height of the tree
     // for each level find the maximum width
     for (int i = 1; i <= height; i++) {
         int width = findWidth(root, i); // find width at ith level
         // update maxwidth
         if (width > maxwidth)
             maxwidth = width;
     }
     return maxwidth;
 }
 int main() // Main function
 {
     struct Node* root = newnode(1); // declare root node
     root->left = newnode(2); // Left child of root
     root->right = newnode(3); // Right child of root
     root->left->left = newnode(4); // Left child of left parent
     root->right->left = newnode(5); // Left child of right parent
     root->right->right = newnode(6); // Right child of right parent
     printf("The maximum width of the tree is %d", max_width(root));
     return 0;
 } 

Output:

The Maximum Width of the Tree is 3

Approach 2

In this approach, we use a queue data structure to count all the nodes at a particular level. The maximum size of the queue will give the maximum width of the tree. Since it will be a level order traversal, all the existing child nodes will be pushed to the queue after each level is traversed.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // Create the tree structure
 class Node {
 public:
     int data; // value of a Node
     Node *left, *right; // The left and right pointers to the Node
 };
 // Function to insert a new node
 Node* newnode(int data)
 {
     Node* root = new Node(); // create root Node
     root->data = data; // insert the value
     root->left = root->right = NULL; // the left and right child are null currently
     return root;
 }
 // Function to find the maximum width
 int max_width(Node* root)
 {
     if (root == NULL) // if the tree has 0 nodes
         return 0;
     int result = 0; // the max_width is set to zero
     queue<Node*> q; // Create a queue to to level order traversal
     q.push(root); // Push root in the queue
     while (!q.empty()) {
         int count = q.size(); // Calculate the current maximum width  and no of nodes
         result = max(count, result); // Update the current maximum with the result
         while (count--) { // Iterate until all nodes are traversed
             Node* temp = q.front(); // Take the front node
             q.pop(); // POP it as we have to find its child nodes
             if (temp->left != NULL) // If left child exist enter in queue
                 q.push(temp->left);
             if (temp->right != NULL) // If right child exist enter in queue
                 q.push(temp->right);
         }
     }
     return result;
 }
 int main()
 {
     Node* root = newnode(1); // declare root node
     root->left = newnode(2); // Left child of root
     root->right = newnode(3); // Right child of root
     root->left->left = newnode(4); // Left child of left parent
     root->right->left = newnode(5); // Left child of right parent
     root->right->right = newnode(6); // Right child of right parent
     cout << "The maximum width of the tree is " << max_width(root);
     return 0;
 } 

Output:

The maximum width of the tree is 3

Time Complexity: O(N) where N is the number of nodes

Space. Complexity: O(max_width) i.e., maximum width of the tree 


Related Topics

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.