#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);
}
void
printLevel(
struct
Node* queue[],
int
index,
int
size)
{
for
(
int
i = index; i < size; i++) {
cout << queue[i]->key <<
" "
;
}
cout << endl;
}
bool
isPalindrome(
struct
Node* queue[],
int
index,
int
size)
{
while
(index < size) {
if
(queue[index++]->key
!= queue[size--]->key)
return
false
;
}
return
true
;
}
void
printPalLevel(
struct
Node* node,
struct
Node* queue[],
int
index,
int
size)
{
cout << queue[index]->key << endl;
while
(index < size) {
int
curr_size = size;
while
(index < curr_size) {
struct
Node* temp = queue[index];
if
(temp->left != NULL) {
queue[size++] = temp->left;
}
if
(temp->right != NULL) {
queue[size++] = temp->right;
}
index++;
}
if
(isPalindrome(queue, index, size - 1)) {
printLevel(queue, index, size);
}
}
}
int
findSize(
struct
Node* node)
{
if
(node == NULL)
return
0;
return
1
+ findSize(node->left)
+ findSize(node->right);
}
void
printPalindromicLevel(
struct
Node* node)
{
int
t_size = findSize(node);
struct
Node* queue[t_size];
queue[0] = node;
printPalLevel(node, queue, 0, 1);
}
int
main()
{
Node* root = newNode(10);
root->left = newNode(13);
root->right = newNode(13);
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->left->left = newNode(21);
root->right->left->right = newNode(22);
root->right->right->left = newNode(22);
root->right->right->right = newNode(21);
root->right->right->right->left = newNode(8);
printPalindromicLevel(root);
return
0;
}