您的位置:首页 > 其它

LC114 Flatten Binary Tree to Linked List

2016-07-28 10:10 120 查看
难点:跟踪前一个节点,正确清除右节点

class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL)
return;
TreeNode* head=root;
stack<TreeNode*> is;
is.push(root);
TreeNode* tmp=root->left;
TreeNode* pre=root;
while(!is.empty()||tmp!=NULL)
{
if(tmp!=NULL)
{
is.push(tmp);
pre=tmp;
tmp=pre->left;
}
else
{
tmp=is.top()->right;
if(tmp!=NULL)
{
if(pre!=is.top())
is.top()->right=NULL;
pre->right=tmp;
pre=tmp;
}
is.pop();
}
}
while(head!=NULL)
{
if(head->left!=NULL)
{
head->right=head->left;
head->left=NULL;
}
head=head->right;
}
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: