diameter of a binary tree

int height(TreeNode* node)
{
if(node==NULL)
return -1;
else
return max(height(node->left)+1,height(node->right)+1);
}

int diameterOfBinaryTree(TreeNode* root) {
if(root==NULL) return 0;

//recursion
//passing through root
long int l_h = height(root->left);
long int r_h = height(root->right);
long int t_h = l_h+r_h+1+1;

//not passing through root
long int l_d = diameterOfBinaryTree(root->left);
long int r_d = diameterOfBinaryTree(root->right);
long int max_val = max(l_d,r_d);

long int res = max(t_h,max_val);

return res;
}

Comments (0)