Given a binary tree and two nodes. The task is to count the number of turns needs to reach from one node to another node of the Binary tree.
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 node
2…Given node present either on the left side or right side or equal to LCA.
…. According to above condition over program falls under two Case.
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 need to reached the target node. Case 2: If one of the nodes is equal to LCA_Node. Then we count only number of turns needs 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 the implementation of above idea.
Time Complexity : O(n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.