[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 helper(TreeNode *root, TreeNode *&pre) {
13         if (root == NULL) return;
14         if (pre != NULL) {
15             pre->left = NULL;
16             pre->right = root;
17         }
18         pre = root;
19         TreeNode *left = root->left;
20         TreeNode *right = root->right;
21         if (left != NULL) {
22             helper(left, pre);
23         }
24         if (right != NULL) {
25             helper(right, pre);
26         }
27     }
28     void flatten(TreeNode *root) {
29         TreeNode *pre = NULL;
30         helper(root, pre);
31     }
32 };

 非递归的话,可以先让当前节点的右儿子指向左儿子,左儿子的最右儿子指向当前节点的原来的右儿子,依次迭代即可。

 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         if (root == NULL) return;
14         TreeNode *cur = root, *pre = NULL;
15         while (cur != NULL) {
16             if (cur->left != NULL) {
17                 pre = cur->left;
18                 while (pre->right) pre = pre->right;
19                 pre->right = cur->right;
20                 cur->right = cur->left;
21                 cur->left = NULL;
22             }
23             cur = cur->right;
24         }
25     }
26 };

 

posted @ 2014-04-05 01:11  Eason Liu  阅读(1361)  评论(0编辑  收藏  举报