Geeksforgeeks

Timer is Running

Associated Course(s):
Amazon SDE Test Series

Given a binary tree and data value of two of its nodes. Find the number of turns needed to reach from one node to another in the given binary tree.

**Example 1:**

Input :Tree = 1 / \ 2 3 / \ / \ 4 5 6 7 / / \ 8 9 10 first node = 5 second node = 10Output:4Explanation :Turns will be at 2, 1, 3, 6.

**Example 2:**

Input :Tree = 1 / \ 2 3 / \ / \ 4 5 6 7 / / \ 8 9 10 first node = 1 second node = 4Output :-1Explanation:No turn is required since they are in a straight line.

**Your Task: **

You don't need to read input or print anything. Complete the function **NumberOFTurns()** which takes root node and data value of 2 nodes as input parameters and returns number of turns required to navigate between them. If the two nodes are in a straight line, ie- the path does not involve any turns, return -1.

**Expected Time Complexity:** O(N)

**Expected Auxiliary Space: **O(Height of Tree)

**Constraints:**

1 ≤ N ≤ 10^3

Author: harshitsidhwa

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

jainshubham52535 | 529 |

Pathak1899 | 436 |

yashdip123 | 380 |

kirtidee18 | 377 |

jots62 | 351 |

kirtidee18 | 1057 |

ykaushik | 752 |

aggarwalvatsal5 | 741 |

harbilassingh | 576 |

pmr_3689 | 570 |

blackshadows | 5456 |

Ibrahim Nash | 5450 |

akhayrutdinov | 5111 |

mb1973 | 4976 |

Quandray | 4827 |

Login to report an issue on this page.