23ms C++ solution that beats 97%


  • 0
    S
    TreeLinkNode* find_first_child(TreeLinkNode* &root)
    {
        while (root) {
            if (root->left) {
                return root->left;
            }
            else if (root->right) {
                return root->right;
            }
            root=root->next;
        }
        return nullptr;
    }
    void connect(TreeLinkNode *root) {
        TreeLinkNode *node=root, *child=find_first_child(node), *firstchild=child;
        while (child) {
            if (child==node->left&&node->right) {
                child->next=node->right;
                child=child->next;
            }
            node=node->next;
            while (node) {
                if (node->left) {
                    child->next=node->left;
                    break;
                }
                else if (node->right) {
                    child->next=node->right;
                    break;
                }
                node=node->next;
            }
            child=child->next;
            if (!child) {
                node=firstchild, child=find_first_child(node), firstchild=child;
            }
        }
    }

Log in to reply
 

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