Flatten Binary Tree to Linked List
LeetCode #114
Description:
Given a binary tree, flatten it to a linked list in-place.
Example:
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Idea:
recursion思想很复杂,如果用stack来iteration做。
push的时候先push右边,再push左边。然后立马把node->left=nullptr
,right subtree就应该是刚push进stack的元素(如果stack not empty).
Code:
class Solution {
public:
void flatten(TreeNode* root) {
stack<TreeNode *> stack_node;
TreeNode *node=root;
if(root!=NULL) stack_node.push(root);
while(!stack_node.empty()){
node=stack_node.top();
stack_node.pop(); // after pop, stack could be empty.
// Push right subtree first, then left subtree!
if(node->right!=NULL) stack_node.push(node->right);
if(node->left!=NULL) stack_node.push(node->left);
node->left=NULL;
if(!stack_node.empty()){
node->right=stack_node.top();
}
}
}
};