[面试真题] 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
Hints: If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
解法 1:非递归解法
 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         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         if(NULL == root){
16             return;
17         }
18         stack<TreeNode*> s;
19         TreeNode *p = root;
20         s.push(root);
21         while(p->left){
22             s.push(p->left);
23             p = p->left;
24         }
25         while(s.size()){
26             TreeNode *cur = s.top();
27             s.pop();
28             if(cur->right){
29                 p->left = cur->right;
30                 cur->right = NULL;
31                 while(p->left){
32                     s.push(p->left);
33                     p = p->left;
34                 }
35             }
36         }
37         p = root;
38         while(p->left){
39             p->right = p->left;
40             p->left = NULL;
41             p = p->right;
42         }
43     }
44 };

Run Status: Accepted!
Program Runtime: 44 milli secs

Progress: 225/225 test cases passed.
 
posted @ 2013-05-12 16:09  infinityu  阅读(173)  评论(0编辑  收藏  举报