Learner Level
Implement the binaryTreeLevelOrderCount method that counts values visited during level order traversal.
The input contains a binary tree represented as an integer array tree in level-order format.
Your task is to return how many levels are present in the tree. This is the same as counting the number of level-order rounds needed to visit all existing nodes.
For example, [3,9,20,0,0,15,7] has three levels, so the answer is 3.
Use breadth-first search to process the tree level by level.
Put the root node into a queue. For each round, process all nodes currently in the queue; those nodes belong to the same level. Add their existing children to the queue for the next round.
Increase the level count after each round. When the queue becomes empty, the count is the number of tree levels.
Pseudocode:
function binaryTreeLevelOrderCount(tree, size):
if size == 0:
return 0
queue = empty queue
push index 0 into queue
levels = 0
while queue is not empty:
count = size of queue
repeat count times:
index = remove front from queue
left = 2 * index + 1
right = 2 * index + 2
if left < size and tree[left] exists:
push left into queue
if right < size and tree[right] exists:
push right into queue
levels++
return levels