Given a Binary Tree, find diameter of it. The diameter of a tree is the number of nodes on the longest path between two leaves in the tree
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
Diameter of a tree
Diameter of a tree is number of nodes on the longest path between two leaves of tree.
Now the fact is the longest path always passes through the root.
In fact no of nodes=height of left subtree (there is the source/destination leaf node) + height of right subtree(there is the destination/source leaf node) + 1(for root)
So actually the solution depends on finding the height of each subtree.
Finding height of each subtree can be done using recursion or level order traversal. However, I prefer level order traversal (BFS rocks!)
Algorithm:
Diameter=height of left subtree + height of right subtree+1
Pre-requisite:
A Queue q for level-order traversal, input binary tree, function to calculate height of subtrees
C++ implementation
Output
Example with explanation: