My Intuitive 8ms C++ Recursive Solution


  • 1
    C
    class Solution {
    public:
    void flatten(TreeNode* root) {
    	if (!root)
    		return;
    	helper(root);
    }
    private:
    
    void helper(TreeNode* root)
    {
    	if (!root)
    		return;
    	if (!root->left && !root->right)
    		return;
    	else if (root->left == NULL && root->right != NULL)
    		helper(root->right);
    	else if (root->right == NULL && root->left != NULL)
    	{
    		helper(root->left);
    		root->right = root->left;
    		root->left = NULL;
    	}
    	else
    	{
    		helper(root->left);
    		helper(root->right);
    		TreeNode* p = root->right;
    		root->right = root->left;
    		root->left = NULL;
    		TreeNode* q = root->right;
    		while (q->right != NULL)
    			q = q->right;
    		q->right = p;
    	}
    }};

Log in to reply
 

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