LC114 Flatten Binary Tree to Linked List

难点:跟踪前一个节点,正确清除右节点

 1 class Solution {
 2 public:
 3     void flatten(TreeNode* root) {
 4         if(root==NULL)
 5             return;
 6         TreeNode* head=root;
 7         stack<TreeNode*> is;
 8         is.push(root);
 9         TreeNode* tmp=root->left;
10         TreeNode* pre=root;
11         while(!is.empty()||tmp!=NULL)
12         {
13             if(tmp!=NULL)
14             {
15                 is.push(tmp);
16                 pre=tmp;
17                 tmp=pre->left;
18             }
19             else
20             {
21                 tmp=is.top()->right;
22                 if(tmp!=NULL)
23                 {
24                     if(pre!=is.top())
25                         is.top()->right=NULL;
26                     pre->right=tmp;
27                     pre=tmp;
28                 }
29                 is.pop();
30             }
31         }
32         while(head!=NULL)
33         {
34             if(head->left!=NULL)
35             {
36                 head->right=head->left;
37                 head->left=NULL;
38             }
39             head=head->right;
40         }
41     }
42 };
View Code

 

posted @ 2016-07-28 10:10  vaevaevae  阅读(157)  评论(0编辑  收藏  举报