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).
Example 1:
Input:
1
/ \
2 3
Output: 3
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output: 4
Ans :
class Solution {
public:
// Function to return the diameter of a Binary Tree.
int h( Node* node)
{
if(!node)
{
return 0;
}
return (max(h(node->left) , h(node->right))+1);
}
// Function to return the diameter of a Binary Tree.
int sum( Node * node)
{
return h(node->left) + h(node->right)+ 1;
}
int max(int a , int b)
{
return (a>b)?a:b;
}
int diameter( Node* root)
{
queue<Node *>q;
q.push(root);
int m = sum(root);
while(!q.empty())
{
m = max(m , sum(q.front()));
if(q.front()->left)
q.push(q.front()->left);
if(q.front()->right)
q.push(q.front()->right);
q.pop();
}
return m;
}
};
refrences :
https://www.geeksforgeeks.org/diameter-tree-using-dfs/
Comments
Post a Comment