My 24ms easy understand recursive solution


  • 0
    X
    class Solution {
    public:
    void connect(TreeLinkNode *root) {
        
        if(!root) return;
        helper(root);
    
        
    }
    void helper(TreeLinkNode * root)
    {
        if(!root->left)return;
        
        root->left->next=root->right;
        mirror(root->left,root->right);
        helper(root->left);
        helper(root->right);
    }
    void mirror(TreeLinkNode* node1, TreeLinkNode* node2)
    {
        if(!node1) return;
        node1->next=node2;
        mirror(node1->right, node2->left);
    }
    };
    

    Another shorter solution taking advantage of using *next.

    class Solution {
    public:
    void connect(TreeLinkNode *root) {
        
        if(!root) return;
        helper(root);
        
    }
    void helper(TreeLinkNode * root)
    {
        if(!root->left)return;
    
        root->left->next=root->right;
        if(root->next)
            root->right->next=root->next->left;
        helper(root->left);
        helper(root->right);
    }
    
    };

Log in to reply
 

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