-2

enter image description here

What the difference between using q != null and !q.isEmpty()?
when I used q!=null in the following code, it's not going to be compiled. But !q.isEmpty() works pretty well.

java

Queue<TreeNode[]> q=new LinkedList<>();
q.add(new TreeNode[]{t1, t2});
while(q!=null){          // is not complied
    TreeNode[] t=q.remove();

    if(t[0]==null || t[1]==null) continue;

    t[0].val+=t[1].val;

    if(t[0].left==null) t[0].left=t[1].left;
    else q.add(new TreeNode[]{t[0].left, t[1].left});

    if(t[0].right==null) t[0].right=t[1].right;
    else q.add(new TreeNode[]{t[0].right, t[1].right});
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 2
    What compilation error are you given? `while (q != null)` should compile (although it makes no sense at all) – Hovercraft Full Of Eels Feb 07 '19 at 04:05
  • But it looks like your main problem is that you don't understand the Java concept of null -- please check out the duplicate for information on this – Hovercraft Full Of Eels Feb 07 '19 at 04:06
  • The error pointed to the line "TreeNode[] t=q.remove();" , showing NoSuchElementException – Cara Jiang Feb 07 '19 at 04:10
  • 1
    Your statements don't make sense as you're in the question stating that the code won't compile, but in comments state that it is throwing an exception, meaning that the code is in fact compiling and running but then throwing an exception. This is all very confusing I'm afraid. – Hovercraft Full Of Eels Feb 07 '19 at 04:12
  • But on the other hand it makes sense that an exception will be thrown if you try to remove an element from an empty collection. This has nothing to do with a compilation problem and you'd best read up on the the difference between these two things. – Hovercraft Full Of Eels Feb 07 '19 at 04:13

1 Answers1

1

'q' will never be null because you already instantiated it with new LinkedList so there will result in an infinite loop. So, in your example, you have to check if the list is empty. But it should compile

prietosanti
  • 181
  • 1
  • 1
  • 10