Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6
1 \ 2 \ 3 \ 4 \ 5 \ 6Answer:
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