Given a binary tree, the task is to print all the palindromic paths of this binary tree.
Palindromic path: Path in which concatenation of data from root to leaf is the same as the leaf to root, such as 1->2->2->1.
Input: 1 / \ 2 3 / / \ 1 6 3 \ / 2 1 Output: 1, 2, 1 1, 3, 3, 1 Explanation: In above binary tree paths 1, 2, 1 and 1, 3, 3, 1 are palindromic paths because traversal of these paths are the same as root to leaf and leaf to root Input: 7 / \ 4 3 / \ \ 3 6 4 / \ \ / 1 4 4 1 / 7 Output: 7, 4, 6, 4, 7 Explanation: In the above binary tree, there is only one path which is same as root to leaf and leaf to root. that is 7->4->6->4->7
Approach: The idea is to use pre-order traversal to traverse the tree and keep track of the path. Whenever a leaf node is reached then check that the current path is a palindromic path or not. Similarly, Recursively Traverse the other sibling nodes of the tree by backtracking the path of the tree. Following are the steps:
- Start the Pre-order traversal of the tree with the root node.
- Check that the current node is not null, if yes then return.
if (node == Null) return;
- Check that the current node is a leaf node or not, if yes then check that the current path is a palindromic path or not.
if (node->left == Null && node->right == Null) isPalindromic(Path);
- Otherwise, If the current node is not a leaf node then recursively traverse the left and right child nodes of the current node.
- To check that a path is palindromic or not, Concatenate the data of the nodes from root to leaf and then check that the formed string is a palindrome or not.
Below is the implementation of the above approach:
2, 8, 8, 2, 2, 8, 5, 8, 2,
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.