[Leetcode 81] 114 Flatten Binary Tree to Linked List

Problem:

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

 

Analysis:

Solution to tree problem is always recursive. So is this problem. First let's see some basic cases:

For node with left and right all equals NULL, we just need to return the node itself;

For a simplest tree [a, b, c], we must return the a b c sequence.

The rule is that, a is the first node of the flattened list, and the left child b is the next and the right child c is the last.

Then, we expand it to general cases: [root, left-tree, right-tree]

  1. root should always be the first node.

  2. the flatterned left-tree is the next of root.

  3. the flatterned right-tree is the next of the last node of the flatterned left-tree.

So, we can see that the need variables are the first and last node of the flatterned list.

How to return two variables in one function? We can return the first node and use an extra function argument to achieve this.

 

Code:

 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     TreeNode *h;
14     if (root != NULL)
15         ftHelper(root, &h);
16 }
17 
18 TreeNode *ftHelper(TreeNode* node, TreeNode **llast) {
19     TreeNode *last = node, *first = node;
20     *llast = node;
21     
22     if (node->left == NULL && node->right == NULL)
23         return node;
24 
25     TreeNode *l = node->left, *r = node->right, *h;
26 
27     if (l != NULL) {
28         node->right = ftHelper(l, &last);
29         node->left = NULL;
30     }
31 
32     if (r != NULL) {
33         last->right = ftHelper(r, &h);
34         last = h;
35     }
36 
37     *llast = last;
38     return first;
39 }
40 };
View Code

 

posted on 2013-07-23 14:19  freeneng  阅读(179)  评论(0编辑  收藏  举报

导航