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).
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 Tree
In 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)
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 contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Diameter of a Binary Tree
- Diameter of a Binary Indexed Tree with N nodes
- Finding the lexicographically smallest diameter in a binary tree
- Diameter of n-ary tree using BFS
- Diameter of an N-ary tree
- Diameter of a tree using DFS
- DP on Trees | Set-3 ( Diameter of N-ary Tree )
- Possible edges of a tree for given diameter, height and vertices
- Make a tree with n vertices , d diameter and at most vertex degree k
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Iterative method to find ancestors of a given binary tree
- Iterative Method to find Height of Binary Tree
- Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
- Iterative Method To Print Left View of a Binary Tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method