The Wayback Machine - https://web.archive.org/web/20241225114251/https://www.geeksforgeeks.org/diameter-of-a-binary-tree/
Open In App

Diameter of a Binary Tree

Last Updated : 22 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary tree, the task is to determine the diameter of the tree. The diameter/width of a tree is defined as the number of edges on the longest path between any two nodes. 

Examples:

Input:

diameter---------of---------a---------binary---------tree---------1

Output: 2
Explanation: The longest path has 2 edges (node 2 -> node 1 -> node 3).

diameter---------of---------a---------binary---------tree---------3


Input:

diameter---------of---------a---------binary---------tree---------2

Output: 4
Explanation: The longest path has 4 edges (node 3 -> node 8 -> node 5 -> node 6 -> node 9).

diameter---------of---------a---------binary---------tree---------4

[Naive Approach] Using Recursion – O(n^2) Time and O(h) Space

The idea is to recursively traverse the tree. For each node, find the height of left subtree and right subtree and compare the diameter (sum of height of left subtree + height of right subtree) with the maximum diameter.

Note: This approach will get time limit exceeded (TLE) error as it is not optimized.

C++
// C++ program to find the diameter
// of a binary tree.
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to compute the height of a tree.
int height(Node* root) {
  
    // Base case: tree is empty
    if (root == nullptr)
        return 0;

    // If tree is not empty then height = 1 +
    // max of left height and right heights
    return 1 + max(height(root->left), 
                   height(root->right));
}

// Function to get diameter of a binary tree
int diameter(Node* root) {
  
    if (root == nullptr)
        return 0;

    // Get the height of left and right
      // sub-trees
    int lheight = height(root->left);
    int rheight = height(root->right);

    // Get the diameter of left and right
      // sub-trees
    int ldiameter = diameter(root->left);
    int rdiameter = diameter(root->right);

    // Return max of the following three:
    // 1) Diameter of left subtree
    // 2) Diameter of right subtree
    // 3) Height of left subtree + height of right subtree
    return max({lheight + rheight, ldiameter, rdiameter});
}

int main() {

    // Constructed binary tree is
    //         1
    //        / \
    //       2   3
    //      / \
    //     4   5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    cout << diameter(root) << endl;

    return 0;
}
C
// C program to find the diameter
// of a binary tree.
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to compute the height of a tree.
int height(struct Node* root) {
    
    // Base case: tree is empty
    if (root == NULL)
        return 0;

    // If tree is not empty then height = 1 +
    // max of left height and right heights
    int leftHeight = height(root->left);
    int rightHeight = height(root->right);
    
    return 1 + 
    (leftHeight > rightHeight ? leftHeight : rightHeight);
}

// Function to get diameter of a binary tree
int diameter(struct Node* root) {
    if (root == NULL)
        return 0;

    // Get the height of left and right sub-trees
    int lheight = height(root->left);
    int rheight = height(root->right);

    // Get the diameter of left and right sub-trees
    int ldiameter = diameter(root->left);
    int rdiameter = diameter(root->right);
    
    // Diameter of current subtree 
    int curr = lheight+rheight;

    // Return max of the following three:
    // 1) Diameter of left subtree
    // 2) Diameter of right subtree
    // 3) Height of left subtree + height of right subtree
    if (ldiameter > rdiameter && ldiameter > curr)
        return ldiameter;
    else if (rdiameter > ldiameter && rdiameter > curr) 
        return rdiameter;
    return curr;
}

struct Node* createNode(int x) {
    struct Node* newNode = 
        (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {
    
    // Constructed binary tree is
    //         1
    //        / \
    //       2   3
    //      / \
    //     4   5
    struct Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    printf("%d\n", diameter(root));

    return 0;
}
Java
// Java program to find the diameter
// of a binary tree.
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to compute the height of a tree.
    static int height(Node root) {
        
        // Base case: tree is empty
        if (root == null)
            return 0;

        // If tree is not empty then height = 1 +
        // max of left height and right heights
        return 1 + Math.max(height(root.left), height(root.right));
    }

    // Function to get diameter of a binary tree
    static int diameter(Node root) {
        if (root == null)
            return 0;

        // Get the height of left and right sub-trees
        int lheight = height(root.left);
        int rheight = height(root.right);

        // Get the diameter of left and right sub-trees
        int ldiameter = diameter(root.left);
        int rdiameter = diameter(root.right);

        // Return max of the following three:
        // 1) Diameter of left subtree
        // 2) Diameter of right subtree
        // 3) Height of left subtree + height
          // of right subtree
        return Math.max(lheight + rheight, 
                        Math.max(ldiameter, rdiameter));
    }

    public static void main(String[] args) {
        
        // Constructed binary tree is
        //         1
        //        / \
        //       2   3
        //      / \
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        System.out.println(diameter(root));
    }
}
Python
# Python program to find the diameter
# of a binary tree.

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to compute the height 
# of a tree.
def height(root):
    
    # Base case: tree is empty
    if root is None:
        return 0

    # If tree is not empty then height = 1 +
    # max of left height and right heights
    return 1 + max(height(root.left), height(root.right))

# Function to get diameter of a binary tree
def diameter(root):
    if root is None:
        return 0

    # Get the height of left and 
    # right sub-trees
    lheight = height(root.left)
    rheight = height(root.right)

    # Get the diameter of left and 
    # right sub-trees
    ldiameter = diameter(root.left)
    rdiameter = diameter(root.right)

    # Return max of the following three:
    # 1) Diameter of left subtree
    # 2) Diameter of right subtree
    # 3) Height of left subtree + height of right subtree
    return max(lheight + rheight, ldiameter, rdiameter)

if __name__ == "__main__":
    
    # Constructed binary tree is
    #         1
    #        / \
    #       2   3
    #      / \
    #     4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    print(diameter(root))
C#
// C# program to find the diameter
// of a binary tree.
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to compute the 
    // height of a tree.
    static int height(Node root) {
        
        // Base case: tree is empty
        if (root == null)
            return 0;

        // If tree is not empty then height = 1 +
        // max of left height and right heights
        return 1 + Math.Max(height(root.left), height(root.right));
    }

    // Function to get diameter of
      // a binary tree
    static int diameter(Node root) {
        if (root == null)
            return 0;

        // Get the height of left and 
          // right sub-trees
        int lheight = height(root.left);
        int rheight = height(root.right);

        // Get the diameter of left and right sub-trees
        int ldiameter = diameter(root.left);
        int rdiameter = diameter(root.right);

        // Return max of the following three:
        // 1) Diameter of left subtree
        // 2) Diameter of right subtree
        // 3) Height of left subtree + height of right subtree
        return Math.Max(lheight + rheight,
                        Math.Max(ldiameter, rdiameter));
    }

    static void Main(string[] args) {
        
        // Constructed binary tree is
        //         1
        //        / \
        //       2   3
        //      / \
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        Console.WriteLine(diameter(root));
    }
}
JavaScript
// JavaScript program to find the diameter
// of a binary tree.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to compute the height of a tree.
function height(root) {

    // Base case: tree is empty
    if (root === null)
        return 0;

    // If tree is not empty then height = 1 +
    // max of left height and right heights
    return 1 + Math.max(height(root.left), height(root.right));
}

// Function to get diameter of a binary tree
function diameter(root) {
    if (root === null)
        return 0;

    // Get the height of left and right sub-trees
    const lheight = height(root.left);
    const rheight = height(root.right);

    // Get the diameter of left and right sub-trees
    const ldiameter = diameter(root.left);
    const rdiameter = diameter(root.right);

    // Return max of the following three:
    // 1) Diameter of left subtree
    // 2) Diameter of right subtree
    // 3) Height of left subtree + height of right subtree
    return Math.max(lheight + rheight, ldiameter, rdiameter);
}

// Constructed binary tree is
//         1
//        / \
//       2   3
//      / \
//     4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

console.log(diameter(root));

Output
3

[Expected Approach] Without Using Height – O(n) Time and O(h) Space

The idea is to optimize the above approach by calculating the height in the same recursive function rather than calculating it separately.

Step by step approach:

  • Initialize a variable ans, which will store the diameter of the tree. (initially set to 0).
  • Recursively traverse the binary tree. For each node, find the height of the left and right subtree. Then compare the sum of (height of left subtree + height of right subtree) with the ans variable. If it is greater than ans, then update the value of ans.

Below is the implementation of the above approach:

C++
// C++ program to find the diameter
// of a binary tree.
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Recursive function which finds the 
// height of root and also calculates 
// the diameter of the tree.
int diameterRecur(Node* root, int &ans) {
  
    // Base case: tree is empty
    if (root == nullptr)
        return 0;
    
    // find the height of left and right subtree
    // (it will also find of diameter for left 
    // and right subtree).
    int lHeight = diameterRecur(root->left, ans);
    int rHeight = diameterRecur(root->right, ans);
    
    // Check if diameter of root is greater
    // than ans.
    ans = max(ans, lHeight+rHeight);
    
    // return the height of current subtree.
    return 1 + max(lHeight, rHeight);
}

// Function to get diameter of a binary tree
int diameter(Node* root) {
  
    int ans = 0;
    
    diameterRecur(root, ans);
    
    return ans;
}

int main() {

    // Constructed binary tree is
    //         1
    //        / \
    //       2   3
    //      / \
    //     4   5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    cout << diameter(root) << endl;

    return 0;
}
Java
// Java program to find the diameter
// of a binary tree.
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function which finds the
    // height of root and also calculates
    // the diameter of the tree.
    static int diameterRecur(Node root, int[] ans) {
        
        // Base case: tree is empty
        if (root == null)
            return 0;

        // find the height of left and right subtree
        // (it will also find of diameter for left
        // and right subtree).
        int lHeight = diameterRecur(root.left, ans);
        int rHeight = diameterRecur(root.right, ans);

        // Check if diameter of root is greater
        // than ans.
        ans[0] = Math.max(ans[0], lHeight + rHeight);

        // return the height of current subtree.
        return 1 + Math.max(lHeight, rHeight);
    }

    // Function to get diameter of a binary tree
    static int diameter(Node root) {
        int[] ans = new int[1];
        diameterRecur(root, ans);
        return ans[0];
    }

    public static void main(String[] args) {

        // Constructed binary tree is
        //         1
        //        / \
        //       2   3
        //      / \
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        System.out.println(diameter(root));
    }
}
Python
# Python program to find the diameter
# of a binary tree.

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Recursive function which finds the
# height of root and also calculates
# the diameter of the tree.
def diameterRecur(root, ans):
    
    # Base case: tree is empty
    if root is None:
        return 0

    # find the height of left and right subtree
    # (it will also find of diameter for left
    # and right subtree).
    lHeight = diameterRecur(root.left, ans)
    rHeight = diameterRecur(root.right, ans)

    # Check if diameter of root is greater
    # than ans.
    ans[0] = max(ans[0], lHeight + rHeight)

    # return the height of current subtree.
    return 1 + max(lHeight, rHeight)

# Function to get diameter of 
# a binary tree
def diameter(root):
    ans = [0]
    diameterRecur(root, ans)
    return ans[0]

if __name__ == "__main__":

    # Constructed binary tree is
    #         1
    #        / \
    #       2   3
    #      / \
    #     4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    print(diameter(root))
C#
// C# program to find the diameter
// of a binary tree.
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function which finds the
    // height of root and also calculates
    // the diameter of the tree.
    static int DiameterRecur(Node root, ref int ans) {
      
        // Base case: tree is empty
        if (root == null)
            return 0;

        // find the height of left and right subtree
        // (it will also find of diameter for left
        // and right subtree).
        int lHeight = DiameterRecur(root.left, ref ans);
        int rHeight = DiameterRecur(root.right, ref ans);

        // Check if diameter of root is greater
        // than ans.
        ans = Math.Max(ans, lHeight + rHeight);

        // return the height of current subtree.
        return 1 + Math.Max(lHeight, rHeight);
    }

    // Function to get diameter of a binary tree
    static int diameter(Node root) {
        int ans = 0;
        DiameterRecur(root, ref ans);
        return ans;
    }

    static void Main(string[] args) {

        // Constructed binary tree is
        //         1
        //        / \
        //       2   3
        //      / \
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        Console.WriteLine(diameter(root));
    }
}
JavaScript
// JavaScript program to find the diameter
// of a binary tree.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Recursive function which finds the
// height of root and also calculates
// the diameter of the tree.
function diameterRecur(root, ans) {

    // Base case: tree is empty
    if (root === null)
        return 0;

    // find the height of left and right subtree
    // (it will also find of diameter for left
    // and right subtree).
    const lHeight = diameterRecur(root.left, ans);
    const rHeight = diameterRecur(root.right, ans);

    // Check if diameter of root is greater
    // than ans.
    ans.value = Math.max(ans.value, lHeight + rHeight);

    // return the height of current subtree.
    return 1 + Math.max(lHeight, rHeight);
}

// Function to get diameter of a binary tree
function diameter(root) {
    const ans = { value: 0 };
    diameterRecur(root, ans);
    return ans.value;
}

// Constructed binary tree is
//         1
//        / \
//       2   3
//      / \
//     4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

console.log(diameter(root));

Output
3

Time Complexity: O(n), where n is the number of nodes in tree.
Auxiliary Space: O(h) due to recursive calls.

Related article:



Next Article

Similar Reads

three90RightbarBannerImg