解法一:recursion DFS
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->left);
flatten(root->right);
if(root->left){
TreeNode* right = root->right;
root->right = root->left;
root->left = NULL;
while(root->right) root = root->right;
root->right = right;
}
}
};
解法二:non-recursion BFS
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* cur = root;
while(cur){
if(cur->left){
TreeNode* temp = cur->left;
while(temp->right) temp = temp->right;
temp->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
}
cur = cur->right;
}
}
};