给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/
2 5
/ \
3 4 6
将其展开为:
1
2
3
4
5
6
class Solution {
public:
TreeNode* last=nullptr;
void flatten(TreeNode* root) {
if(root==nullptr)return;
flatten(root->right);
flatten(root->left);
root->right=last;
root->left=nullptr;
last=root;
}
};
class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL)return;
flatten(root->left);
flatten(root->right);
TreeNode* tmp=root->right;
root->right=root->left;
root->left=NULL;
while(root->right!=NULL)root=root->right;
root->right=tmp;
}
};