Diameter of a Binary Tree in O(n) [A new method]

30 Jun, 2021
The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are colored (note that there may be more than one path in the tree of the same diameter). 
Examples: 
Input :     1
          /   \
        2      3
      /  \
    4     5

Output : 4

Input :     1
          /   \
        2      3
      /  \ .    \
    4     5 .    6

Output : 5
We have discussed a solution in below post. Diameter of a Binary TreeIn this post a new simple O(n) method is discussed. Diameter of a tree can be calculated by only using the height function, because the diameter of a tree is nothing but maximum value of (left_height + right_height + 1) for each node. So we need to calculate this value (left_height + right_height + 1) for each node and update the result. Time complexity – O(n)  
C++
Java
Python3
C#
Javascript
// Simple C++ program to find diameter// of a binary tree.#include <bits/stdc++.h>using namespace std; /* Tree node structure used in the program */struct Node {    int data;    Node* left, *right;}; /* Function to find height of a tree */int height(Node* root, int& ans){    if (root == NULL)        return 0;     int left_height = height(root->left, ans);     int right_height = height(root->right, ans);     // update the answer, because diameter of a    // tree is nothing but maximum value of    // (left_height + right_height + 1) for each node    ans = max(ans, 1 + left_height + right_height);     return 1 + max(left_height, right_height);} /* Computes the diameter of binary tree with given root. */int diameter(Node* root){    if (root == NULL)        return 0;    int ans = INT_MIN; // This will store the final answer    height(root, ans);    return ans;} struct Node* newNode(int data){    struct Node* node = new Node;    node->data = data;    node->left = node->right = NULL;     return (node);} // Driver codeint main(){    struct Node* root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->left->right = newNode(5);     printf("Diameter is %d\n", diameter(root));     return 0;}
// Simple Java program to find diameter// of a binary tree.class GfG { /* Tree node structure used in the program */static class Node{    int data;    Node left, right;} static class A{    int ans = Integer.MIN_VALUE;} /* Function to find height of a tree */static int height(Node root, A a){    if (root == null)        return 0;     int left_height = height(root.left, a);     int right_height = height(root.right, a);     // update the answer, because diameter of a    // tree is nothing but maximum value of    // (left_height + right_height + 1) for each node    a.ans = Math.max(a.ans, 1 + left_height +                    right_height);     return 1 + Math.max(left_height, right_height);} /* Computes the diameter of binarytree with given root. */static int diameter(Node root){    if (root == null)        return 0;     // This will store the final answer    A a = new A();    int height_of_tree = height(root, a);    return a.ans;} static Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;     return (node);} // Driver codepublic static void main(String[] args){    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);     System.out.println("Diameter is " + diameter(root));}} // This code is contributed by Prerna Saini.
# Simple Python3 program to find diameter# of a binary tree. class newNode:    def __init__(self, data):        self.data = data        self.left = self.right = None # Function to find height of a treedef height(root, ans):    if (root == None):        return 0     left_height = height(root.left, ans)     right_height = height(root.right, ans)     # update the answer, because diameter    # of a tree is nothing but maximum    # value of (left_height + right_height + 1)    # for each node    ans[0] = max(ans[0], 1 + left_height +                             right_height)     return 1 + max(left_height,                   right_height) # Computes the diameter of binary# tree with given root.def diameter(root):    if (root == None):        return 0    ans = [-999999999999] # This will store                          # the final answer    height_of_tree = height(root, ans)    return ans[0] # Driver codeif __name__ == '__main__':    root = newNode(1)    root.left = newNode(2)    root.right = newNode(3)    root.left.left = newNode(4)    root.left.right = newNode(5)     print("Diameter is", diameter(root)) # This code is contributed by PranchalK
// Simple C# program to find diameter// of a binary tree.using System; class GfG{ /* Tree node structure used in the program */class Node{    public int data;    public Node left, right;} class A{    public int ans = int.MinValue;} /* Function to find height of a tree */static int height(Node root, A a){    if (root == null)        return 0;     int left_height = height(root.left, a);     int right_height = height(root.right, a);     // update the answer, because diameter of a    // tree is nothing but maximum value of    // (left_height + right_height + 1) for each node    a.ans = Math.Max(a.ans, 1 + left_height +                    right_height);     return 1 + Math.Max(left_height, right_height);} /* Computes the diameter of binarytree with given root. */static int diameter(Node root){    if (root == null)        return 0;     // This will store the final answer    A a = new A();    int height_of_tree = height(root, a);    return a.ans;} static Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;     return (node);} // Driver codepublic static void Main(){    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);     Console.WriteLine("Diameter is " + diameter(root));}} /* This code is contributed by Rajput-Ji*/
<script>     // Simple Javascript program to find    // diameter of a binary tree.         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         let ans = Number.MIN_VALUE;         /* Function to find height of a tree */    function height(root)    {        if (root == null)            return 0;         let left_height = height(root.left);         let right_height = height(root.right);         // update the answer, because diameter of a        // tree is nothing but maximum value of        // (left_height + right_height + 1) for each node        ans = Math.max(ans, 1 + left_height +                        right_height);         return 1 + Math.max(left_height, right_height);    }     /* Computes the diameter of binary    tree with given root. */    function diameter(root)    {        if (root == null)            return 0;         // This will store the final answer        let height_of_tree = height(root);        return ans;    }     function newNode(data)    {        let node = new Node(data);        return (node);    }         let root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);      document.write("Diameter is " + diameter(root));     </script>
Diameter is 4
This article is contributed by Pooja Kamal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
prerna saini
Rajput-Ji
PranchalKatiyar
kenadam2505
jarvis365
rameshtravel07
Amazon
Cadence India
Directi
MakeMyTrip
Microsoft
Oracle
OYO Rooms
Philips
Salesforce
Snapdeal
VMWare
Tree
VMWare
Amazon
Microsoft
OYO Rooms
Snapdeal
MakeMyTrip
Oracle
Directi
Philips
Salesforce
Cadence India
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 2 (Properties)
Lowest Common Ancestor in a Binary Tree | Set 1
Decision Tree
Diagonal Traversal of Binary Tree
Construct Tree from given Inorder and Preorder traversals
Insertion in a Binary Tree in level order
BFS vs DFS for Binary Tree