Don't know where is wrong


  • 0
    F
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root == null) return;
            Deque<TreeLinkNode> queue1 = new ArrayDeque<>();
            Deque<TreeLinkNode> queue2 = new ArrayDeque<>();
            queue1.push(root);
            int level = 0;
            while(!queue1.isEmpty() || !queue2.isEmpty()) {
                if(level % 2 == 0) {
                    TreeLinkNode fir = queue1.pop();
                    if(fir.left != null) queue2.push(fir.left);
                    if(fir.right != null) queue2.push(fir.right);
                    while(!queue1.isEmpty()) {
                        TreeLinkNode sec = queue1.pop();
                        fir.next = sec;
                        if(sec.left != null) {
                            queue2.push(sec.left);
                        }
                        if(sec.right != null) {
                            queue2.push(sec.right);
                        }
                        fir = sec;
                    }
                    level++;
                }
                else {
                    TreeLinkNode fir = queue2.pop();
                    if(fir.left != null) queue1.push(fir.left);
                    if(fir.right != null) queue1.push(fir.right);
                    while(!queue2.isEmpty()) {
                        TreeLinkNode sec = queue2.pop();
                        fir.next = sec;
                        if(sec.left != null) {
                            queue1.push(sec.left);
                        }
                        if(sec.right != null) {
                            queue1.push(sec.right);
                        }
                        fir = sec;
                    }
                    level++;
                }
            }
        }
    }
    

Log in to reply
 

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