Failed in this test case


  • 0
    H

    Here is the code I wrote:

    class Solution {public:
    void flatten(TreeNode *root) {
        if(root == NULL)
            return;
        TreeNode *rTree = root->right;
        if(root->left != NULL)
        {
            root->right =root->left;
            root->left = NULL;
            flatten(root->right);
        }
        if(rTree != NULL)
        {
            root->right = rTree;
            flatten(root->right);
        }
    }
    

    };

    and here is the output info:
    Input:
    {1,2,3}

    Output:
    {1,#,3}

    Expected:
    {1,#,2,#,3}

    What seems to be the problem? I can't figure out.


  • 0
    Q

    you have to cache the deepest node of left tree and make it as the start of right tree.

    declare the member TreeNode *start since flatten cannot return any value.
    if(root->left != NULL)
    {
    root->right =root->left;
    root->left = NULL;
    if (root->right)
    start = root->right;
    flatten(root->right);
    }
    if(rTree != NULL)
    {
    start->right = rTree;
    start->left = NULL;
    flatten(start->right);
    }


  • 0
    H

    Thanks a lot!


Log in to reply
 

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