I have some doubts about running time of following question. The problem is printing a binary tree level by level. For example if tree is like
5 / \ 2 6 / \ \ 7 1 8
Then the output should be like
5 2 6 7 1 8
TreeNode structure is very simple and looks like below;
public class TreeNode {
public TreeNode left;
public TreeNode right;
public int value;
public TreeNode(int value) {
this.value = value;
}
}
And the code is shown below:
public void printByLevel(TreeNode root) {
if (root == null) {
throw new IllegalArgumentException();
}
Queue<TreeNode> current = new LinkedList<>();
current.add(root);
while (!current.isEmpty()) {
Queue<TreeNode> parents = current;
current = new LinkedList<>();
// print parents
for (TreeNode parent : parents) {
System.out.print(parent.value + " ");
}
System.out.println();
// construct next level by adding children of each parent
for (TreeNode parent : parents) {
if (parent.left != null) {
current.add(parent.left);
}
if (parent.right != null) {
current.add(parent.right);
}
}
}
}
Now can I say running time of this algorithm is \$O(N)\$ because every is node processed only once? Or should I say it is \$O(m*N)\$, where \$m\$ refers to number of nodes at the current level because I am printing nodes at each level?