I’ve written the following BFS for a tree in Java:
public class Node
{
public int value;
public ArrayList<Node> myChildren = new ArrayList<Node>();
public Node(int v)
{
value = v;
}
}
public Node breadthFirstSearch(Node root, int value)
{
if(root == null) return null;
Queue<Node> nodesToVisit = new LinkedList<Node>();
nodesToVisit.add(root);
while(nodesToVisit.size() > 0)
{
Node currentNode = nodesToVisit.remove();
if(currentNode.value == value) return currentNode;
nodesToVisit.addAll(currentNode.myChildren);
}
return null;
}
My question is, does it matter (in terms of runtime complexity or some other factor) when I “visit” the node if(currentNode.value == value). I could either visit the node after I’ve popped it off the queue, or before I put it on the queue.
No, it doesn’t matter (much).
You’re basically talking about the order of these two lines:
For performance and code clarity, returning early is always a good thing, so I would leave your code as it is.
If you reversed the order of these lines, you would incur the extra cost of the call to
addAll(), which would however be negligible.