Javatpoint Logo
Javatpoint Logo

Maximum Width of a Binary Tree

The maximum width of a binary tree can be defined as the maximum number of the nodes of the binary tree that are present in a particular level of the binary tree. To calculate the maximum width of a binary tree, we need to traverse the tree level and find the maximum number of nodes present at a particular level.

Let's see an example to understand better the concept of a binary tree's maximum width in a better way.

Maximum Width of a Binary Tree

In the binary tree displayed above, the root node has value 42 and has its left subtree and right subtree. In this example, let's calculate the number of nodes present in each binary tree level. The binary tree displayed above has levels starting from level 0 to level 4 (with five levels).

  • Only a root node is present in level 0 of the shown binary tree, so the number of nodes in level 0 is 1.
  • In level 1 of the binary tree, there are two child nodes (right child and left child) of the root node having values 29 and 89, respectively, so level 1 of the binary tree has two nodes.
  • There are three nodes in level 2 of the binary tree (two child nodes of the left subtree root and one right child node of the right subtree root), so there are three nodes in level 2 of the binary tree.
  • In level 3 of the binary tree, we have two nodes that are child nodes with a value of 99.
  • In the last level, i.e. level 4 of the binary tree, two nodes are present.

So, the numbers of nodes in each level are:

Level 0: 1 Node

Level 1: 2 Nodes

Level 2: 3 Nodes

Level 3: 2 Nodes

Level 4: 2 Nodes.

So, level 2 has the maximum number of nodes that are 3, three nodes having values 1, 35 and 99, respectively. As level 2 has 3 nodes, the maximum width of a binary tree displayed above in the image is three.

It is not compulsory that all the time, the deepest level should have the maximum number of nodes of the tree, three, and the maximum width of a binary tree is found there. Like in the binary tree shown above, level 2, which is not the deepest level of the binary tree, having the maximum number of nodes (3 nodes).

C++ Code

Let's write a C++ code better to understand the maximum width of a binary tree.

Output: Run the above code, and it gives the following output.

The Maximum width of the binary tree is 3.

Java Code

To understand the maximum width of a binary tree, let's write a Java code.

Output: The output of the above code is:

The Maximum width of the binary tree = 3.

Python Code:

To understand the maximum width of a binary tree, let's write a python code to find the width of a given binary tree.

Output: The output of the above code is:

The Maximum width of the binary tree is 3.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA