Find direction of path followed from root by a linked list in a Binary Tree

• Last Updated : 22 Nov, 2021

Given root of the Binary Tree T and a linked list L, the task is to find the direction of path followed from root such that there exists a path from root to any leaf node of the Tree such that the values is that path forms the Linked List. If there doesn’t exist any such path then print “-1”.

Note: The path taken in the left direction is denoted by L and the path taken in the right direction is R.

Examples:

Input: LL = 1 -> 2 -> 5 -> 8
1
/    \
2      3
/  \    /  \
4    5 6    8
/
8
Output: L R L
Explanation:
The path of linked list in binary tree is as follows:
1
/    \
2      3
/  \    /  \
4    5 6    8
/
8

Input: LL = 1 -> 2 -> 4
1
/    \
2      2
/  \    /  \
4    5 6    8
/
8
Output: {L, L}

Approach: The given problem can be solved by traversing the binary tree and linked list simultaneously, if the current node doesn’t match with the current node of the linked list, then that path is incorrect. Otherwise, check for the other order for the valid paths. Follow the steps below to solve the given problem:

• Declare a function, say findPath(root, head, path) and perform the following steps in this function:
• If root is NULL or the root’s value is not the same as the head’s node value, then return false.
• If the current root node is the leaf node and head is the last node then return true.
• Insert the character ‘L’ in the vector path[] and recursively call for the left subtree as findPath(root->left, head->next, path) and if the value return by this function is true, then there exists a path and return true from the function. Otherwise, pop the last character from the vector path[].
• Insert the character ‘R’ in the vector path[] and recursively call for the right subtree as findPath(root->right, head->next, path) and if the value return by this function is true, then there exists a path and return true from the function. Otherwise, pop the last character from the vector path[].
• Otherwise, return false from the function.
• Initialize a vector, say path[] that stores the direction if Linked List is found in the given binary tree.
• Call for the function findPath(root, head, path).
• If the size of the vector path is 0, then print “-1”. Otherwise, print the path stored in the vector path[].

Below is the implementation of the above approach:

C#

Output:
L R L

Time Complexity: O(N + M), where N is number of nodes in Binary Tree and M is length of the Linked List
Auxiliary Space: O(H), where H is the height of binary tree

My Personal Notes arrow_drop_up