void
method with out-parameter
The traverseLevels
method is practically a void
method with an out-parameter List<Node>
that it populates.
In many practical cases, including your program in question,
a better option is to make the method return the out-parameter as its result.
Move common logic to higher level
In this code:
listOfNodes.add(root);
while(!nodes.isEmpty()){
root= nodes.poll();
if (root.left!=null) {
listOfNodes.add(root.left);
nodes.add(root.left);
}
if (root.right!=null) {
listOfNodes.add(root.right);
nodes.add(root.right);
}
}
You add the root to listOfNodes
,
and then add the branches.
That is, you are adding to the list at 3 places.
You could refactor this to add to the list at once place, right after polling:
while (!nodes.isEmpty()) {
root = nodes.poll();
listOfNodes.add(root);
if (root.left != null) {
nodes.add(root.left);
}
if (root.right != null) {
nodes.add(root.right);
}
}
This is simpler, shorter, and the outcome is equivalent.
Bad comments