#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
int
key;
struct
Node *left, *right;
};
Node* newNode(
int
key)
{
Node* temp =
new
Node;
temp->key = key;
temp->left = temp->right = NULL;
return
(temp);
}
int
findHeight(
struct
Node* node)
{
if
(node == NULL)
return
0;
int
leftHeight = findHeight(node->left);
int
rightHeight = findHeight(node->right);
return
1 + (leftHeight > rightHeight ?
leftHeight : rightHeight);
}
bool
isPalindrome(string str)
{
int
l = 0;
int
h = str.length() - 1;
while
(h > l)
{
if
(str[l++] != str[h--])
{
return
false
;
}
}
return
true
;
}
bool
isPathPal(
int
* path,
int
index)
{
int
i = 0;
string s;
while
(i <= index) {
s += to_string(path[i]);
i += 1;
}
return
isPalindrome(s);
}
void
printPalPath(
int
* path,
int
index)
{
for
(
int
i = 0; i < index; i++) {
cout << path[i] <<
", "
;
}
cout << endl;
}
void
printPath(
struct
Node* node,
int
* path,
int
index)
{
if
(node == NULL) {
return
;
}
path[index] = node->key;
printPath(node->left, path,
index + 1);
printPath(node->right, path,
index + 1);
if
(node->left == NULL &&
node->right == NULL) {
if
(isPathPal(path, index)) {
printPalPath(path, index + 1);
}
}
}
void
PalindromicPath(
struct
Node* node)
{
int
height = findHeight(node);
int
* path =
new
int
[height];
memset
(path, 0,
sizeof
(path));
printPath(node, path, 0);
}
void
createAndPrintPalPath(){
Node* root = newNode(2);
root->left = newNode(6);
root->right = newNode(8);
root->right->left = newNode(8);
root->right->right = newNode(5);
root->right->left->left = newNode(1);
root->right->left->right = newNode(2);
root->right->right->left = newNode(3);
root->right->right->right = newNode(8);
root->right->right->right->left = newNode(2);
PalindromicPath(root);
}
int
main()
{
createAndPrintPalPath();
return
0;
}