Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void flatten(TreeNode *root) {
if (root == NULL)
return;
stack<TreeNode*>StackNode;
StackNode.push(root);
TreeNode* Prenode = new TreeNode(0);
TreeNode* Curnode = NULL;
while (!StackNode.empty())
{
Curnode = StackNode.top();
StackNode.pop();
Prenode->left = NULL;
Prenode->right = Curnode;
Prenode = Curnode;
if (Curnode->right)
StackNode.push(Curnode->right);
if (Curnode->left)
StackNode.push(Curnode->left);
}
}