题目链接
void flatten(TreeNode *root) {
vector<TreeNode*> nodes;
nodes.push_back(root);
while(!nodes.empty())
{
TreeNode* cur_node = nodes.back();
TreeNode* left_child = NULL;
TreeNode* right_child = NULL;
if(cur_node != NULL)
{
left_child = cur_node->left;
right_child = cur_node->right;
}
nodes.pop_back();
if(right_child != NULL)
{
nodes.push_back(right_child);
}
if(left_child != NULL)
{
nodes.push_back(left_child);
}
if(!nodes.empty())
{
cur_node->left = NULL;
cur_node->right = nodes.back();
}
}
}
参考Binary Tree Preorder Traversal的方法。