Wednesday, September 10, 2014

Flatten BT to linked list -- Leetcode

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
Answer:
Using recursion, need O(n) space.

class Solution {
public:
    void flatten(TreeNode *root) {
         TreeNode *end = flattenHelp(root);
         return;
    }
   
    TreeNode* flattenHelp(TreeNode* root){
        if(!root) return NULL;
   
        TreeNode *left = root->left;
        TreeNode *right = root -> right;
       
        if(!left && !right) return root;
       
        else if(!left && right){
            return flattenHelp(right);
        }
       
        else if(left && !right){
             TreeNode *leftend = flattenHelp(left);
             root->right = left;
             root->left = NULL;
             return leftend;
        }
        else{
        TreeNode *leftend = flattenHelp(left);
        TreeNode *rightend = flattenHelp(right);
        root->right = left;
        root->left = NULL;
        leftend ->right = right;
        return rightend;
        }
    }
};

No comments:

Post a Comment