// Recursion
class Solution {
public:
    void flatten(TreeNode *root) {
        if (!root) return;
        if (root->left) flatten(root->left);
        if (root->right) flatten(root->right);
        TreeNode *tmp = root->right;
        root->right = root->left;
        root->left = NULL;
        while (root->right) root = root->right;
        root->right = tmp;
    }
};
class Solution {
public:
    void flatten(TreeNode* root) {
        if (!root) return;
        stack<TreeNode*> s;
        s.push(root);
        while (!s.empty()) {
            TreeNode *t = s.top(); s.pop();
            if (t->left) {
                TreeNode *r = t->left;
                while (r->right) r = r->right;
                r->right = t->right;
                t->right = t->left;
                t->left = NULL;
            }
            if (t->right) s.push(t->right);
        }
    }
};

相关文章:

  • 2021-12-18
  • 2021-10-16
  • 2022-01-26
  • 2022-02-25
  • 2021-09-04
  • 2022-01-30
  • 2022-02-19
  • 2022-12-23
猜你喜欢
  • 2021-08-05
  • 2021-09-01
  • 2021-12-10
  • 2022-01-05
相关资源
相似解决方案