C++ solution using recursion


  • 4
    F

    Recursively add the left subtree to the right subtree.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.