Just get the path from LCA to the node and count the number of turns in the route using two bool values right and left.
2 special conditions:
if the given two nodes are not LCA then we have to add one more turn to the answer.
if the given node is LCA and they are in same line then the answer should be -1
Sample Input:
3
1 2 3
2 3
1 2 3 4 5 6 7 8 N N N 9 10 N N
5 10
1 2 3 4 5 6 7 8 N N N 9 10 N N
1 4
Sample Output:
1
4
-1
Explanation:
Case 2.
Given Binary Tree and two nodes 5 & 10
1
/ \
2 3
/ \ / \
4 5 6 7
/ / \
8 9 10
Number of Turns needed to reach from 5 to 10 is 4.
For the above tree, if two nodes are 1 & 4, the output will be -1 since they are in a straight line
Number of Turns in Binary Tree is very insteresting problem .I get similar idea .First i find lca(lowest common ancenster) and then find number of turn in binary tree.
#include<bits/stdc++.h>
Node *solve(struct Node * root,int first,int second)
{
if(root==NULL)return NULL;
if(root->data==first||root->data==second)return root;
struct Node *left=solve(root->left,first,second);
struct Node *right=solve(root->right,first,second);
if(!left&&!right)return NULL;
if(left&&right) return root;
return left!=NULL ?left:right;
}
void findlength(struct Node *root,int target,int flag,int &ans,int bend)
{
if(!root)return ;
if(root->data==target)
ans=bend;
findlength(root->left,target,0,ans,(flag)?bend+1:bend);
findlength(root->right,target,1,ans,(flag)?bend:bend+1);
}
int NumberOFTurns(struct Node* root, int first, int second)
{
int ans=0;
struct Node *ancs=solve(root,first,second);
int l=0,r=0;
if(ancs->data==first)
{
l=0;
}
else
{
findlength(ancs->left,first,0,l,0);
findlength(ancs->right,first,1,l,0);
}
if(ancs->data==second)
{
r=0;
}
else
{
findlength(ancs->right,second,1,r,0);
findlength(ancs->left,second,0,r,0);
}
if(ancs->data!=first&&ancs->data!=second)
return l+r+1;
if(l+r)
return r+l;
return -1;
}