Given a binary tree, target node X and a string patt. The task is to find the last node of the binary tree following the pattern starting from X. Pattern may contain only five types of character ‘p’, ‘l’, ‘r’, ‘m’ and ‘n’. For any character encountered:
- p: Get to the parent of the current node.
- l: Get to the left child of the current node.
- r: Get to the right child of the current node.
- m: Get to the left sibling in the same level.
- n: Get to the right sibling in the same level.
Note that if the node doesn’t exist corresponding to any character then skip that character and remain on the current node.
Input: 10 / \ 12 13 / \ 14 15 / \ / \ 21 22 23 24 X = 14, patt = "npmrprrlm" Output: 22 Starting from the target node 14 n: 14 -> 15 p: 15 -> 13 m: 13 -> 12 r: 12 -> 12 (there is no right child) p: 12 -> 10 r: 10 -> 13 r: 13 -> 15 l: 15 -> 23 m: 23 -> 22 Input: 5 / \ 16 8 X = 16, patt = "pppp" Output: 5
- Create an auxiliary tree from the original tree but include three extra pointers (parent pointer, left and right sibling pointers).
- Parent pointer will point to the parent of the current node.
- Left pointer will point to the left sibling.
- Right pointer will point to the right sibling.
- Check the image below:
- After creation of this tree, we can easily traverse the given pattern.
- If any node doesn’t exist corresponding any character then simply skip that character.
Below is the implementation of the above approach: