c++ simple solution


  • 0
    A
    void connect(TreeLinkNode *root) {
            if (!root ) return;
            TreeLinkNode *beg = root, *cur = root, *next = root;
            bool found = true;
            while (beg) {
                // find next level begin node
                if (!found && cur && (cur->left || cur->right)) {
                    if (cur->left) {
                        next = cur->left;
                        found = true;
                    } else {
                        next = cur->right;
                        found = true;
                    }
                }
                
                // next level
                if (!cur) {
                    beg = next;
                    cur = beg;
                    found = false;
                    next = NULL;
                    continue;
                }
                
                // same level
                // same subtree
                if (cur->left && cur->right) {
                    cur->left->next = cur->right;   
                }
                // different subtree
                if (cur->left || cur->right) {
                    TreeLinkNode *tmp = cur->next;
                    while (tmp) {
                        if (!tmp->left && !tmp->right) {
                            tmp = tmp->next;
                            continue;
                        } else {
                            break;
                        }
                    }
                    
                    
                    if (tmp) {
                        TreeLinkNode *to = tmp->left ? tmp->left : tmp->right;
                        TreeLinkNode *from = cur->right ? cur->right : cur->left;
                        from->next = to;
                    }
                    
                }
                
                cur = cur->next;
            }
        }
    

Log in to reply
 

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