My simple direct c++ code


  • 0
    Y

    With a helper, the code became easy and direct.

    void connect(TreeLinkNode *root) {
        if(root == NULL)
            return;
        root->next = nullptr;
        // cc(root->left, root->right);
        if(root->left)
            root->left->next = root->right;
        helper(root->left);
        helper(root->right);
    }
    void helper(TreeLinkNode *now){
        if(now == NULL)
            return;
        // cc(now->left, now->right);
        if(now->left){
            now->left->next = now->right;
            if(now->next == NULL)
                now->right->next = NULL;
            else
                now->right->next = now->next->left;
            helper(now->left);
            helper(now->right);
        }
    }

Log in to reply
 

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