Easy 15 lines solution with diameter tree concept


The trick is to use the diameter of the tree concept, but here we just need a little tweak, we want that our diameter to always picks up the given leaf node with value B.

So when the recursive call, comes to the leaf, I return a very high value, and it will ensure that my leaf node always gets picked up.

int fun(TreeNode* root, int &res, int B){
if(!root) return 0;
if(root->left==NULL && root->right==NULL && root->val==B) return (10000000);
int l=fun(root->left, res, B);
int r=fun(root->right, res, B);
int temp=1+ max(l, r);
int ans=max(temp, l+r+1);
res= max(ans, res);
return temp;
int Solution::solve(TreeNode* A, int B) {
int res=0;
fun(A, res, B);
return res-10000000;