![]() |
VOOZH | about |
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.
- Find the LCA of given two nodes
- 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.
4
Time Complexity: O(n)
Alternate Solution:
We have to follow the step:
- Find the LCA of the given two nodes
- 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.
- Reverse one of the strings and concatenate both strings.
- Count the number of time characters in our resultant string not equal to its adjacent character.
Implementation:
4
Time Complexity: O(n)