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 firstname.lastname@example.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.
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 an N-ary tree
- Diameter of a tree using DFS
- Diameter of n-ary tree using BFS
- Possible edges of a tree for given diameter, height and vertices
- DP on Trees | Set-3 ( Diameter of N-ary Tree )
- 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
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- 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
- Binary Tree to Binary Search Tree Conversion using STL set