题目描述:
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
代码:
void flatten(TreeNode *root)
{
if(root == NULL)
return;
stack<TreeNode *> treenode_stack;
TreeNode * pre;
TreeNode * next;
pre = root;
next = NULL;
if(root->right != NULL)
treenode_stack.push(root->right);
if(root->left != NULL)
treenode_stack.push(root->left);
while(!treenode_stack.empty())
{
TreeNode * node = treenode_stack.top();
treenode_stack.pop();
next = node;
pre->right = next;
pre->left = NULL;
pre = node;
if(node->right != NULL)
treenode_stack.push(node->right);
if(node->left != NULL)
treenode_stack.push(node->left);
}
}LeetCode:Flatten Binary Tree to Linked List
原文地址:http://blog.csdn.net/yao_wust/article/details/41478653