The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).
The diameter of a tree T is the largest of the following quantities:
* the diameter of T’s left subtree
* the diameter of T’s right subtree
* the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T)
Time Complexity: O(n^2)
Diameter of the given binary tree is 4
Optimized implementation: The above implementation can be optimized by calculating the height in the same recursion rather than calling a height() separately. Thanks to Amar for suggesting this optimized version. This optimization reduces time complexity to O(n).
Time Complexity: O(n)
Asked in: Amazon, Cadence, MakeMyTrip, Microsoft, Oracle, Philips, Prop Tiger, Sales Force, Snapdeal, VMWare
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Diameter of a Binary Tree in O(n) [A new method]
- Diameter of a Binary Indexed Tree with N nodes
- Finding the lexicographically smallest diameter in a binary tree
- Diameter of a tree using DFS
- Diameter of n-ary tree using BFS
- Diameter of an N-ary tree
- 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
- Minimum swap required to convert binary tree to binary search tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Check if a binary tree is subtree of another binary tree | Set 2
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 1
- Difference between Binary Tree and Binary Search Tree
- Check whether a binary tree is a full binary tree or not
Improved By : shweta44