C++ 5-line recursive solution (Pre-order Traversal) beat 99.45% DFS


  • 1

    Populate the next pointer for left and right children of the root first (if any of them exists), then use recursive call to process each subtree.

        void connect(TreeLinkNode *r) {
            if (!r) return;
            if (r->left) r->left->next = r->right;
            if (r->right) r->right->next = (r->next)? r->next->left : NULL;
            connect(r->left);
            connect(r->right);
        }
    

  • 0
    L

    @zzg_zzm
    This line is so beautiful.
    if (r->right) r->right->next = (r->next)? r->next->left : NULL;


Log in to reply
 

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