Simple C++ solution


  • 1
    Y
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if (root == NULL)
                return;
    
            if (root->right == NULL && root->left == NULL)
                return;
    
            if (root->right) {
                flatten(root->right);
            }
    
            if (root->left) {
                flatten(root->left);
            }
    
            if (root->right && root->left) {
                TreeNode *lastRightFromLeftNode = root->left;
                while (lastRightFromLeftNode->right) {
                    lastRightFromLeftNode = lastRightFromLeftNode->right;
                }
                lastRightFromLeftNode->right = root->right;
            }
    
            if (root->left) {
                root->right = root->left;
                root->left = NULL;
            }
        }
    };
    

Log in to reply
 

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