Tuesday, September 16, 2014

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.

I. Iterative solution

1. Find the right-most node of left child of cur
2. Set cur->right as the right-most node's right child
3. Set cur->left child as the right child
4. Set cur->left NULL
5. Set cur to be cur->right
6. Go to 1 until all nodes are flattened.

class Solution {
public:
    void flatten(TreeNode *root) {
        while(root){
            if (root->left){
                TreeNode *pre = root->left;
                while(pre->right)
                   pre = pre->right;
                pre->right = root->right;
                root->right = root->left;
                root->left = NULL;
            }
            root=root->right;
        }
    }
};

2.  root 所代表树变成链表后,tail 跟在该链表后面
class Solution {
public:
    void flatten(TreeNode *root) {
        helper(root, NULL);
    }
   
    TreeNode *helper(TreeNode *root, TreeNode *tail){
        if (NULL==root) return tail;
       
        root->right = helper(root->left, helper(root->right, tail));
        root->left = NULL;
        return root;
    }
};

No comments:

Post a Comment