C++ recursive solution with comments

  • 0
        void flatten(TreeNode* root) {
            if (!root) return;
            TreeNode* temp_right = root->right;     // cache the right subtree
            root->right = root->left;               // move the left subtree to the right
            root->left = NULL;                      // null the left subtree
            flatten(root->right);                   // recurse on the right subtree
            while (true) {
                if (!root->right) break;            // find the right most node after flattening
                root = root->right;
            root->right = temp_right;               // link the cached right subtree
            flatten(root->right);                   // recurse the on the attached right subtree

Log in to reply

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