方法一

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;
    }
};

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2021-12-29
  • 2022-01-06
  • 2021-09-29
  • 2021-07-21
猜你喜欢
  • 2021-06-24
  • 2021-12-05
  • 2021-12-11
  • 2021-05-01
  • 2021-11-14
  • 2021-07-01
相关资源
相似解决方案