C++ accepted solution


  • 0
    X
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if (root == NULL) return;
            TreeLinkNode * firstLevel = root;
            TreeLinkNode * nextLevel = firstLevel->left != NULL ? firstLevel->left : firstLevel->right;
            while (nextLevel != NULL) {
                while (firstLevel != NULL) {
                    TreeLinkNode * p = firstLevel->next;
                    while (p != NULL && (p->left == NULL && p->right == NULL)) p = p->next;
                    
                    if (firstLevel->left != NULL && firstLevel->right != NULL) {
                        firstLevel->left->next = firstLevel->right;
                        if (p != NULL)
                            firstLevel->right->next = (p->left != NULL ? p->left : p->right);
                    } else if (firstLevel->left != NULL) {
                        if (p != NULL)
                            firstLevel->left->next = (p->left != NULL) ? p->left : p->right;
                    } else if (firstLevel->right != NULL) {
                        if (p != NULL)
                            firstLevel->right->next = (p->left != NULL) ? p->left : p->right;
                    }
                    
                    firstLevel = firstLevel->next;
                }
                
                firstLevel = nextLevel;
                //find the next level first node
                TreeLinkNode * p = firstLevel;
                while (p != NULL && (p->left == NULL && p->right == NULL)) p = p->next;
                if (p != NULL)
                    nextLevel = p->left != NULL ? p->left : p->right;
                else
                    nextLevel = NULL;
            }
        }
    };

Log in to reply
 

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