Thursday, April 18, 2013

Leetcode: Flatten Binary Tree to Linked List in C++



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.

Solution:

void preorder(TreeNode* root, vector<TreeNode *>& result)
    {
            result.push_back(root);
            if(root->left)
            preorder(root->left, result);
            if(root->right)
            preorder(root->right, result);
    }
    void flatten(TreeNode *root) {
        if(!root)
            return;
        vector<TreeNode *> result;
        preorder(root,result);
        for(int i=0;i<result.size()-1;i++)
        {
            result[i]->left = NULL;
            result[i]->right = result[i+1];
        }
        result[result.size()-1]->left = NULL;
        result[result.size()-1]->right =NULL;
    }

No comments:

Post a Comment