Short code, use level order traverse, could someone please figure out what's wrong here?


  • 0
    B
    class Solution {
    public:
            void connect(TreeLinkNode *root){
                    queue<TreeLinkNode *> Q;
                    if (root)
                            Q.push(root);
                    // counters of nodes in current level and next level
                    int cur_cnt = 1, next_cnt = 0;
    
                    while (!Q.empty()) {
                            TreeLinkNode *node = Q.front(); Q.pop();
                            if (!node->left && !node->right) {
                                    Q.push(node->left);
                                    Q.push(node->right);
                                    next_cnt += 2;
                            }
                            // last node in current level
                            if (!(--cur_cnt)) {
                                    cur_cnt = next_cnt;
                                    next_cnt = 0;
                                    continue;
                            }
                            node->next = Q.front();
                    }
            }
    };

Log in to reply
 

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