#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
lengthOfLongestPath(
struct
Node* node)
{
if
(node == NULL)
return
0;
int
left = lengthOfLongestPath(node->left);
int
right = lengthOfLongestPath(node->right);
return
1 + (left > right ? left : right);
}
void
copyPath(
int
* path,
int
index,
int
** mtrx,
int
row)
{
for
(
int
i = 0; i < index; i++) {
mtrx[row][i] = path[i];
}
}
void
storePath(
struct
Node* node,
int
* path,
int
index,
int
** mtrx,
int
& row)
{
if
(node == NULL) {
return
;
}
path[index] = node->key;
storePath(node->left, path,
index + 1, mtrx, row);
storePath(node->right, path,
index + 1, mtrx, row);
if
(node->left == NULL
&& node->right == NULL) {
row = row + 1;
copyPath(path, index + 1,
mtrx, row);
}
}
int
totalPath(Node* node)
{
static
int
count = 0;
if
(node == NULL) {
return
count;
}
if
(node->left == NULL
&& node->right == NULL) {
return
count + 1;
}
count = totalPath(node->left);
return
totalPath(node->right);
}
void
traverse_matrix(
int
** mtrx,
int
height,
int
width)
{
int
j = 0, k1 = 0, k2 = 0;
int
k3 = height - 1;
int
k4 = width - 1;
for
(
int
round = 0; round < height/2; round++)
{
for
(j = k2; j < width; j++) {
if
(mtrx[k1][j] != INT_MAX) {
cout << mtrx[k1][j] <<
" "
;
}
}
cout << endl;
k2 = 0;
k1++;
for
(j = k4; j >= 0; j--) {
if
(mtrx[k3][j] != INT_MAX) {
cout << mtrx[k3][j] <<
" "
;
}
}
cout << endl;
k4 = width - 1;
k3--;
}
if
(height % 2 != 0) {
for
(j = k2; j < width; j++) {
if
(mtrx[k1][j] != INT_MAX) {
cout << mtrx[k1][j] <<
" "
;
}
}
}
}
void
PrintPath(Node* node)
{
int
max_len = lengthOfLongestPath(node);
int
total_path = totalPath(node);
int
* path =
new
int
[max_len];
memset
(path, 0,
sizeof
(path));
int
** mtrx =
new
int
*[total_path];
for
(
int
i = 0; i < total_path; i++)
{
mtrx[i] =
new
int
[max_len];
}
for
(
int
i = 0; i < total_path; i++)
{
for
(
int
j = 0; j < max_len; j++)
{
mtrx[i][j] = INT_MAX;
}
}
int
row = -1;
storePath(node, path, 0, mtrx, row);
traverse_matrix(mtrx, total_path,
max_len);
free
(mtrx);
}
int
main()
{
Node* root = newNode(10);
root->left = newNode(13);
root->right = newNode(11);
root->right->left = newNode(19);
root->right->right = newNode(23);
root->right->left->left = newNode(21);
root->right->left->right = newNode(29);
root->right->right->left = newNode(43);
root->right->right->right = newNode(15);
root->right->right->right->left = newNode(7);
PrintPath(root);
return
0;
}