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:
- Burn the binary tree starting from the target node
- Search a node in Binary Tree
- K-th ancestor of a node in Binary Tree | Set 3
- K-th ancestor of a node in Binary Tree
- Kth ancestor of a node in binary tree | Set 2
- Sum of cousins of a given node in a Binary Tree
- Get Level of a node in a Binary Tree
- Find mirror of a given node in Binary tree
- Kth node in Diagonal Traversal of Binary Tree
- Total sum except adjacent of a given node in a Binary Tree
- Closest leaf to a given node in Binary Tree
- Postorder successor of a Node in Binary Tree
- Print cousins of a given node in Binary Tree
- Inorder Successor of a node in Binary Tree
- Preorder predecessor of a Node in Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.