Binary tree level-order traversal

problem [https://leetcode.com/problems/binary-tree-level-order-traversal/ 102. Binary Tree Level Order Traversal].

Problem description
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:

Given binary tree , 3   / \   9  20     /  \    15   7

Return its level order traversal as: [  [3],   [9,20],   [15,7] ]

Analysis
We can use breadth-first search to do this problem, by maintaining a BFS queue.

We can maintain an array to produce the output. Each element of this array is also an array that contains the nodes of the same level.

When we process each level of nodes:
 * 1) Record the number of nodes in the current level.
 * 2) Pop each node from current level one by one from the BFS queue, and add the popped nodes to the same-level array. At the same time, add all children of nodes of current level to the BFS queue.
 * 3) After processing each level, add the same-level array to the output array.

Repeat until the BFS queue is empty, i.e. all nodes are processed.

Example
Input: 1         / \        2     3       / \   / \      4   5 6   7

Output: [ [1],  [2, 3],  [4, 5, 6, 7], ]

Time complexity
Since each node is traversed once, the time complexity is O(n).

Space complexity

 * Stack
 * The space complexity on stack is O(1) because there is no recursion involved.


 * Heap
 * We used a BFS queue. The worst case is a perfect binary tree: layer 1 has 1 node, layer 2 has 2 nodes, layer 3 has 4 nodes, layer 4 has 8 nodes, …, and layer k has $$2^{k-1}$$ nodes. In other words, the maximum number of elements in the queue is one half of the total number of nodes in the tree.
 * So the space complexity on heap is O(n).

The total space complexity is O(n).