方法一
class Solution {
public:
void flatten(TreeNode *root) {
TreeNode *now = root;
while (now) {
if (now->left) {
TreeNode *p = now->left;
while (p->right) p = p->right;
p->right = now->right;
now->right = now->left;
now->left = nullptr;
}
now = now->right;
}
}
};
方法二
class Solution {
public:
void dfs(TreeNode *root, vector<TreeNode *> &ans) {
if (root == nullptr)
return;
ans.push_back(root);
dfs(root->left, ans);
dfs(root->right, ans);
}
void flatten(TreeNode *root) {
if (root == nullptr)
return;
vector<TreeNode *> ans;
dfs(root, ans);
for (int x = 0; x < ans.size() - 1; ++x) {
ans[x]->left = nullptr;
ans[x]->right = ans[x + 1];
}
ans[ans.size() - 1]->left = nullptr;
ans[ans.size() - 1]->right = nullptr;
}
};