#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);
}
void
findWidth(
struct
Node* node,
int
& maxValue,
int
& minValue,
int
hd)
{
if
(node == NULL)
return
;
if
(hd > maxValue) {
maxValue = hd;
}
if
(hd < minValue) {
minValue = hd;
}
findWidth(node->left, maxValue, minValue, hd - 1);
findWidth(node->right, maxValue, minValue, hd + 1);
}
void
BFS(
int
** mtrx,
struct
Node* node)
{
queue<
struct
Node*> qu;
qu.push(node);
int
i = -1, j = -1;
struct
Node* poped_node = NULL;
while
(!qu.empty()) {
i++;
int
qsize = qu.size();
while
(qsize--) {
j++;
poped_node = qu.front();
mtrx[i][j] = poped_node->key;
qu.pop();
if
(poped_node->left != NULL) {
qu.push(poped_node->left);
}
if
(poped_node->right != NULL) {
qu.push(poped_node->right);
}
}
j = -1;
}
}
void
traverse_matrix(
int
** mtrx,
int
height,
int
width)
{
int
up = (height / 2);
int
down = up + 1;
bool
flag =
true
;
int
k = 0;
for
(
int
j = 0; j < width; j++) {
if
(mtrx[up][j] != INT_MAX) {
cout << mtrx[up][j] <<
", "
;
}
}
cout << endl;
up--;
for
(
int
i = 0; i < (height - 1); i++) {
if
(flag) {
k = up;
up--;
flag = !flag;
}
else
{
k = down;
down++;
flag = !flag;
}
for
(
int
j = 0; j < width; j++) {
if
(mtrx[k][j] != INT_MAX) {
cout << mtrx[k][j] <<
", "
;
}
}
cout << endl;
}
}
void
printPattern(
struct
Node* node)
{
int
max_value = INT_MIN;
int
min_value = INT_MAX;
int
hd = 0;
findWidth(node, max_value, min_value, hd);
int
width = max_value +
abs
(min_value);
int
height = findHeight(node);
int
** mtrx =
new
int
*[height];
for
(
int
i = 0; i < height; i++) {
mtrx[i] =
new
int
[width];
}
for
(
int
i = 0; i < height; i++) {
for
(
int
j = 0; j < width; j++) {
mtrx[i][j] = INT_MAX;
}
}
BFS(mtrx, node);
traverse_matrix(mtrx, height, width);
free
(mtrx);
}
int
main()
{
Node* root = newNode(10);
root->left = newNode(12);
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(23);
root->right->right->right = newNode(24);
printPattern(root);
return
0;
}