VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-turns-reach-one-node-binary-tree/

⇱ Number of turns to reach from one node to other in binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of turns to reach from one node to other in binary tree

Last Updated : 15 Sep, 2023

Given a binary tree and two nodes. The task is to count the number of turns needed to reach from one node to another node of the Binary tree.

Examples: 

Input: Below Binary Tree and two nodes
 5 & 6 
 1
 / \
 2 3
 / \ / \
 4 5 6 7
 / / \
 8 9 10
Output: Number of Turns needed to reach 
from 5 to 6: 3
 
Input: For above tree if two nodes are 1 & 4
Output: Straight line : 0 turn 

Idea based on the Lowest Common Ancestor in a Binary Tree 

We have to follow the step.

  1. Find the LCA of given two nodes
  2. Given node present either on the left side or right side or equal to LCA. 
    • According to the above condition, our program falls under one of the two cases 
Case 1:  
If none of the nodes is equal to
LCA, we get these nodes either on
the left side or right side. 
We call two functions for each node.
....a) if (CountTurn(LCA->right, first, 
 false, &Count)
 || CountTurn(LCA->left, first, 
 true, &Count)) ; 
....b) Same for second node.
....Here Count is used to store number of 
turns needed to reach the target node. 

Case 2:  
If one of the nodes is equal to LCA_Node,
then we count only the number of turns needed
to reached the second node.
If LCA == (Either first or second)
....a) if (countTurn(LCA->right, second/first, 
 false, &Count) 
 || countTurn(LCA->left, second/first, 
 true, &Count)) ; 


3... Working of CountTurn Function
// we pass turn true if we move 
// left subtree and false if we 
// move right subTree 

CountTurn(LCA, Target_node, count, Turn)

// if found the key value in tree 
if (root->key == key)
 return true;
case 1: 
 If Turn is true that means we are 
 in left_subtree 
 If we going left_subtree then there 
 is no need to increment count 
 else
 Increment count and set turn as false 
case 2:
 if Turn is false that means we are in
 right_subtree 
 if we going right_subtree then there is
 no need to increment count else
 increment count and set turn as true.

// if key is not found.
return false;
 

Below is the implementation of the above idea. 


Output
4

Time Complexity: O(n)

Alternate Solution:

We have to follow the step:

  1. Find the LCA of the given two nodes
  2. Store the path of two-node from LCA in strings S1 and S2 that will store 'l'  if we have to take a left turn in the path starting from LCA to that node and 'r' if we take a right turn in the path starting from LCA.
  3. Reverse one of the strings and concatenate both strings.
  4. Count the number of time characters in our resultant string not equal to its adjacent character.

Implementation:


Output
4

Time Complexity: O(n) 

Comment
Article Tags:
Article Tags: