Maximum Width of a Binary TreeThe 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. 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).
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++ CodeLet'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 CodeTo 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. Next TopicTypes of Graph in Data Structure |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India