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     void flatten(TreeNode *root) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         if(root == NULL)
 5             return; 
 6         flatten(root->left);
 7         flatten(root->right);
 8         if(root->left){
 9             TreeNode *tmp = root->left;
10             while(tmp->right){
11                 tmp = tmp->right;
12             }
13             tmp->right = root->right;
14             root->right = root->left;
15         }
16         root->left = NULL;
17     }

 

posted on 2013-11-08 21:27  waruzhi  阅读(174)  评论(0编辑  收藏  举报

导航