using
namespace
std;
#include <iostream>
#include <stdlib.h>
struct
Node {
int
data;
struct
Node* left;
struct
Node* right;
};
Node* AllocNode(
int
data)
{
Node* temp =
new
Node;
temp->left = NULL;
temp->right = NULL;
temp->data = data;
return
temp;
}
void
PrintInorderBinaryTree(Node* root)
{
if
(root == NULL)
return
;
PrintInorderBinaryTree(root->left);
std::cout << root->data <<
" "
;
PrintInorderBinaryTree(root->right);
}
void
FlattenBinaryTree(Node* root, Node** last)
{
if
(root == NULL)
return
;
Node* left = root->left;
Node* right = root->right;
if
(root != *last) {
(*last)->right = root;
(*last)->left = NULL;
*last = root;
}
FlattenBinaryTree(left, last);
FlattenBinaryTree(right, last);
if
(left == NULL && right == NULL)
*last = root;
}
int
main()
{
Node* root = AllocNode(1);
root->left = AllocNode(2);
root->left->left = AllocNode(3);
root->left->right = AllocNode(4);
root->right = AllocNode(5);
root->right->right = AllocNode(6);
std::cout <<
"Original inorder traversal : "
;
PrintInorderBinaryTree(root);
std::cout << std::endl;
Node* last = root;
FlattenBinaryTree(root, &last);
std::cout <<
"Flattened inorder traversal : "
;
PrintInorderBinaryTree(root);
std::cout << std::endl;
return
0;
}