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

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

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

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.

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: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

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

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

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: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a 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 bubble sort technique...

4 minutes read.