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
\
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL)
return;
stack<TreeNode*> node_stack;
node_stack.push(root);
TreeNode* new_root=NULL;
TreeNode* cur=NULL;
TreeNode* next=NULL;
while(!node_stack.empty()){
cur=node_stack.top();
node_stack.pop();
if(cur->right!=NULL)
node_stack.push(cur->right);
if(cur->left!=NULL)
node_stack.push(cur->left);
if(new_root==NULL){
new_root=cur;
next=cur;
cur->left=NULL;
}else {
next->right=cur;
next->left=NULL;
next=cur;
}
}
root=new_root;
}
};