Diameter of a Binary Tree
- Difficulty Level : Medium
- Last Updated : 17 Jul, 2022
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 the 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)
Diameter of the given binary tree is 4
Time Complexity: O(n2)
Auxiliary Space: O(n) for call stack
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).
Diameter of the given binary tree is 3
Time Complexity: O(n)
Auxiliary Space: O(n) due to recursive calls.
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.