LeetCode:Flatten Binary Tree to Linked List

题目链接

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

分析:按照树的先序遍历顺序把节点串联起来即可,代码如下                                                           本文地址

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  * int val;
 5  * TreeNode *left;
 6  * TreeNode *right;
 7  * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void flatten(TreeNode *root) {
13         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         if(root == NULL)return ;
16         stack<TreeNode *> S;
17         S.push(root);
18         TreeNode *pre = NULL;
19         while(S.empty() == false)
20         {
21             TreeNode *p = S.top();
22             S.pop();
23             if(pre != NULL)
24             {
25                 pre->right = p;
26                 pre->left = NULL;
27             }
28             if(p->right)S.push(p->right);
29             if(p->left)S.push(p->left);
30             pre = p;
31         }
32         pre->left = NULL;
33         pre->right = NULL;
34     }
35 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3440032.html