C++ Recursive solution very easy to understand


  • 0
    Q
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if(root == nullptr)
                return;
            help(root);
        }
        
        TreeNode* help(TreeNode *root){
            if(root == nullptr || (root->left == nullptr && root->right == nullptr))
                return root;
            
            TreeNode *temp = root->right,*temp1 = root->left, *t = root;
            root->left = nullptr;
            root->right = help(temp1);
            
            while(root->right)
                root = root->right;
            root->right = help(temp);
            return t;
        }
    };
    

Log in to reply
 

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