Where did I get Wrong?


  • 0
    N

    It said Null pointer but I could not find the problem

    public class Solution {

    public void connect(TreeLinkNode root) {
    
        if(root==null) return;
        LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        queue.add(root);
        
        while(!queue.isEmpty()){
            int nodeNumber = queue.size();
            while (nodeNumber>0){
                TreeLinkNode cur = queue.poll();
                
                if(nodeNumber==1) cur.next = null;
                else cur.next = queue.peek();
                if(cur.left!=null){
                    queue.add(cur.left);
                }
                if(cur.right!=null){
                    queue.add(cur.right);
                }
            }
        }
        
    }
    

    }


  • 0
    J

    Your inner loop should be an infinite one. Because nodeNumber never updated. You need to modify it by yourself.
    `while (nodeNumber>0){
    TreeLinkNode cur = queue.poll();

            if(nodeNumber==1) cur.next = null;
            **nodeNumber--;**
            else cur.next = queue.peek();
            if(cur.left!=null){
                queue.add(cur.left);
            }
            if(cur.right!=null){
                queue.add(cur.right);
            }
        }`

Log in to reply
 

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