How To Calculate Diameter of Binary Tree?

How to calculate diameter of binary tree?

While learning Data Structures, you might have gone through the Trees Concept, especially the Binary Tree. In that particular course, you learned how to implement a Binary Tree and to work with it. However, along with that, have you learned about the “Diameter Of Binary Tree?”

You might be thinking about how there can be a Diameter Of A Binary Tree. After all, the Binary Tree is not a Circular Structure where the Diameter can exist. But the reality is that you can compute the Diameter of a Binary Tree Theoretically and even with Programming.

This article will first learn about the Diameter Of a Binary Tree and its different types. Later, we will discuss the Theoretical Process followed by the Practical Implementation Process. So, let us start our journey.

Summary Or Key Highlights:

  • A Binary Tree is the only tree where only Two Nodes can be associated with the Root.

  • Some of the key aspects of a Binary Tree are the Node Root, Left Child, Right Child, and Number Of Edges.

  • The diameter of a binary tree is considered to be the longest path in that structure.

  • We can find two kinds of Diameter Of A Binary Tree by analyzing the Root Node.

  • To compute the length of the Longest Path between any two nodes through programming, we have to use the Recursive nature property.

What Is A Binary Tree (BT) In Data Structures?

Now, before we start discussing the Diameter of the Tree, let us have some brief insights about the Binary Tree first. In any case, if the Number of Nodes in a Tree is Less than or Equal to 2, then the tree will be known as the Binary Tree. So, in a BT, there should always be Two Nodes.

Binary Tree (BT) In Data Structures

Key Concepts:

  • Root Node Or Parent Node: The Root is the Main Node in the Binary Tree concept. With the Root, the Left Subtree and Right Subtree are attached. The Root is present in the Middle and the Topmost position.

  • Left Child Of Root: The Left Child of the Root is considered the Root of the Left Subtree. That means, from the Left Child of the Root, the entire Left Subtree is defined and if you want to go inside the Left Subtree, you have to use this Left Child.

  • Right Child Of Root: As with the Left Child, there is the Right Child also present in a Root. The Right Child is the Root of the Right Subtree. And if we want to go inside the Right Subtree, we should have to use it.

  • Edges: Edges are the Lines by which the Nodes in a tree are connected. The Edges play an important role in finding the diameter of the tree. We have to compute the number of edges between two nodes to get the length of the longest path.

Longest Path Of Left And Right Subtrees:

Also, along with these concepts, there is another important concept present, which is known as the Subtree Longest Path. The maximum value between the Root and the endmost Node of any subtree is known as the Subtree Longest Path in the Binary Tree.

There are two longest paths present in a Binary Tree. They will be the Left Subtree’s Longest Path and the Right Subtree’s Longest Path. The Longest Paths will be calculated by counting the number of edges in that path.

What Is The Diameter Of A Binary Tree? Read Below

Now, it is time to discuss the Diameter of Binary Tree. To find the Diameter of a Tree, we have to use the Longest Paths concept. In simple words, the length of the Longest Path between any Two End Nodes will be used as the Diameter of the tree.

You Have To Mark The Difference: The Longest Paths are calculated from the Root to the End Node of any subtree. But in this case, the longest path between the Left Subtree End Node and the Right Subtree End Node will be considered as the Diameter of a Binary Tree.

In this case, as well, we have to count the number of edges. Let us make this more clear with some of the examples and their types in the following section.

What Are Different Types Of Diameter Of A Binary Tree?

Here, we are going to discuss two different types of Diameters one can get in a BT. Here, we will use examples as well that will clear the concept. Let us first start with the Pass through the Root Diameter. Later, we will discuss the next one.

1. Pass Through The Root Node:

In the Pass through the Root case, the Max Path (Diameter) will Go Through the Root. This means the Max Path will count the Root as well, as one of the nodes for making that Longest path.

Pass Through The Root Node Binary Tree

Given a Binary Tree, where we can see the Max Path between any two nodes is going through the Root (Colored Orange). Two Leave Nodes (Colored Green) that indicate the Start and End Points of the path.

The Tree is the length of 4 Paths (The Maximum Length of the Path is 4), so the Total Diameter is 4.

2. Not Passing Through Node Root:

In this case, the Max Path (Diameter) will not use the Root. This type of Diameter is very rare. The Structure of the Tree in such cases is very weird. For all the trees, where any subtree is more developed than the other subtree shows this type of diameter.

Not Passing Through Node Root Binary Tree

Given a Binary Tree, where we can see the Root is not under consideration to make the Max Path. In this case, the Tree is the length of Path 4 (The Maximum Length of the Path is 4), so the Total Diameter is 4. Here, a total of 5 Nodes are present in this path without the Node.

How To Implement A Code To Get The Maximum Diameter Of A Binary Tree?

Whatever we have discussed till now, it is time to incorporate them. Here, we will use Recursively calculate the maximum path or Diameter of a BT. For that purpose, we will use Three Different Programming Languages.

First, we will write the code in the C Programming Language which will help us to understand the logic.

Later, we will move ahead with Other Programming Languages like Java and Python. In the end, we will discuss the Common Explanation of all three codes.

So, let us check the first code which is developed with the help of Structures in C Language.

1. Find The Diameter Of The Binary Tree (BT) Using C Programming Language:

				
					#include <stdio.h>  
#include <stdlib.h>
// For Using C++ Language, we can use the Namespace Std;

struct node // Structure For Binary Tree Node
{ 
    int data; // Int Val or Data To Get The Current Node Or New Node Values
    struct node *left, *right; // Pointer For Left And Right Subtree
};

struct node* newNode(int data); // Recursion Stack Space For New Node Root
int height(struct node* node); // Declaration Of Function Height

int max(int a, int b) // Function To Calculate Maximum Depth Or Maximum Value
{ 
    return (a > b) ? a : b; // When Maximum Diameter Found, Return It
}

int diameter(struct node* tree) // Finding Binary Tree Int Diameter Path
{
    if (tree == NULL) // If Treenode Root Is Null, It Will Return Int 0
    {
        return 0;
    }
    int val; // Ans Variable

    int lh = height(tree->left); // Then Height Function Used For Left Subtree
    int rh = height(tree->right); // Then Height Function Used For Right Subtree

    // We Will Use The Same Recursive Function For Both Left And Right Subtree
    int ld = diameter(tree->left); 
    int rd = diameter(tree->right);

    return max(lh + rh + 1, max(ld, rd)); // Return The Current Diameter Of The Tree 
}

int height(struct node* node) // Function To Get Height Of The Current Subtree
{
    if (node == NULL) // If Treenode Root Is Null, Then Return The Null Data
    {
        return 0;
    }

    // If Treenode Root Is Not Null, Then Return The Path Length
    return 1 + max(height(node->left), height(node->right)); // Find Maximum Height
}

struct node* newNode(int data) // Function To Add Number Of Nodes In A Tree
{
    // First, Create The Binary Tree Node Root And Provide Values There
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data; 
    node->left = NULL; // Create A New Node In The Root Left
    node->right = NULL; // Create A New Node In The Root Right

    return (node); 
}

int main() 
{
    // Given A Binary Tree Using Input Data Call Stack
    struct node* root = newNode(10); // Current Node Root
    // Giving Values To Two Nodes, Left And Right Children
    root->left = newNode(8);
    root->right = newNode(30);
    // Giving More Input Int Values To Create Left And Right Subtrees
    root->left->left = newNode(5);
    root->right->right = newNode(40);
    int val;

    // When Maximum Diameter Found, We Have To Print It To Current Node
    printf("The Diameter Of Binary Tree: %d",diameter(root));
    return 0;
}
				
			

2. Find The Diameter Of The Binary Tree (BT) Using Java Programming Language:

				
					// We Can Also Use Public Int Diameterofbinarytree Public Class Solution
public class Main { 

    static class Node { // Creating The Node As Structure
        int d;
        Node l, r;

        Node(int data) { // Function To Add New Nodes
            this.d = data;
            this.l = null;
            this.r = null;
        }
    }
 
    // Public Class Solution For Finding Out The Max Integers
    
    int max(int a, int b) {
        return (a > b) ? a : b;
    }

    // Function To Find Out The Height Of The Tree
    
    int height(Node nd) {
        if (nd == null) {
            return 0;
        }
        return 1 + max(height(nd.l), height(nd.r));
    }

    // Function To Get The Diameter Of The Subtrees
    
    int diameter(Node tr) {
        if (tr == null) {
            return 0;
        }

        // public int diameter;
        int lh = height(tr.l);
        int rh = height(tr.r);

        int ld = diameter(tr.l);
        int rd = diameter(tr.r);

        return max(lh + rh + 1, max(ld, rd)); // Share The Complete Class Solution Node Root
    }

    public static void main(String[] args) {
        Main tr = new Main(); // We Can Also Rename It As Public Int diameterofbinarytree

        // Providing The Node Values
        Node root = new Node(10);
        root.l = new Node(8);
        root.r = new Node(30);
        root.l.l = new Node(5);
        root.r.r = new Node(40);

        System.out.println("The Diameter Of Binary Tree: " + tr.diameter(root));
    }
}
				
			

3. Find The Diameter Of The Binary Tree (BT) Using Python Programming Language:

				
					class Node: # Function That Will Act As The Structure
    def __init__(self, d):
        self.d = d
        self.l = None
        self.r = None

# Function For Finding Out The Max Integers

def max(a, b):
    return a if a > b else b

# Function To Find Out The Height Of The Tree

def height(node):
    if node is None:
        return 0
    return 1 + max(height(node.l), height(node.r))

# Function To Get The Diameter Of The Subtrees

def diameter(tr):
    if tr is None:
        return 0

    lh = height(tr.l)
    rh = height(tr.r)

    ld = diameter(tr.l)
    rd = diameter(tr.r)

    return max(lh + rh + 1, max(ld, rd))

# Main code
if __name__ == "__main__":
    
    root = Node(10)
    root.l = Node(8)
    root.r = Node(30)
    root.l.l = Node(5)
    root.r.r = Node(40)

    print(f"The Diameter Of Binary Tree: {diameter(root)}")
				
			

Common Explanation Of The Programs:

  • To find the Diameter, first, we need to take a Structure or Class for taking the Nodes. Here, one Int Value will be taken, and Two Pointers will be considered.

  • A function needs to be declared which will Add a New Node to the tree. This will help to first develop the BT there.

  • After creating the BT, we have declared one function that helps to find out the Height of the BT or any Subtree. In the function, we have written the formula of the BT Height. If the Tree is Null, the function will not execute.

  • Now, after that, we will start implementing the function for the Diameter of BT. If the Tree is Null, the function will not execute.

  • As per the theory, we will use the Recursion to find out the Height of the Left Subtree. Then, we will find out the Height of the Right Subtree. For both of these cases, we have to call the Height().

  • Later, we have to recursively call the Diameter Function for Left and Right Subtree. With all of these values, we have to get the Max one, which we will return to the Main Function.

  • Now, in the Main Function, we will insert a New Node into the BT. We have to provide Int Data there.

  • At last, the Diameter() Function will be called, where we will provide the Root as the Current Node. And this entire statement should be written in Printf() to get the output promptly.

Common Output:

Common Output

What Are Some Real-World Use Cases for Calculating the Diameter of a Binary Tree?

If you are thinking that there is no real use in finding the BT Diameter, then you are thinking wrong. There are a lot of applications present. Now, before we conclude our discussion, let us check the following points where we have discussed the Real-world application of BT Diameter.

  • To find out the Network Latency, we have to use the BT Diameter Calculation.

  • For the development of Social Media Platforms, the BT Diameter will be used.

  • In Biological Studies, the BT Diameter helps to find out the Diversity of any System.

  • In Road Transportation, finding out the Longest Paths can be done with the help of BT Diameter.

  • In Telecommunications, the Maximum Signal Delay can be found using this Diameter.

Conclusion:

In the end, we can say it is very important to know about the “Diameter Of Binary Tree”.

However, we advise you to first clear up the basic understanding of the Tree Data Structure and BT. Then, moving on to such a complex topic will be appropriate. Otherwise, you will find the BT Diameter insights difficult to grasp and understand.

Takeaways:

  • The Diameter of BT might go through the Node Root which is very common.

  • In some rare cases, the Diameter of BT might not go through the Node Root.

  • To calculate the Largest diameter, we first must find the height of the subtrees from the root.

  • Later, these heights from the Root will be combined to get the Diameter of the entire BT.

  • The Time Complexity will be O(n), and the Space Complexity will be O(h).

Leave a Comment

Your email address will not be published. Required fields are marked *