This is a code for level order traversal:
public void bfsTraveral() {
if (root == null) {
throw new NullPointerException("The root cannot be null.");
}
int currentLevelNodes = 0;
int nextLevelNodes = 0;
final Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
currentLevelNodes++;
while(!queue.isEmpty()) {
final TreeNode node = queue.poll();
System.out.print(node.element + ",");
currentLevelNodes--;
if (node.left != null) { queue.add(node.left); nextLevelNodes++;}
if (node.right != null) { queue.add(node.right); nextLevelNodes++;}
if (currentLevelNodes == 0) {
currentLevelNodes = nextLevelNodes;
nextLevelNodes = 0;
System.out.println();
}
}
In my opinion the space complexity should be O(2^h), where h is height of tree, simply because that is a max size attainable by the queue during execution. Over the internet I find the space complexity as O (n). It sounds incorrect to me. Please share your opinion.
Thanks,