BFS 的核心就是使用 队列 来确保从上到下的遍历

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型二维数组
  */
function levelOrder( root ) {
    // write code here
    if(root == null) return [];
    const que = [];
    const result = [];
    que.push(root)
    while(que.length != 0) {
        const size = que.length;
        const level = [];
      // 遍历每一层
        for(let i = 0; i < size; i++) {
            const cur = que.shift();
            level.push(cur.val)
          	// 加入下一层的节点,在二叉树中只有左右节点
            if(cur.left != null) {
                que.push(cur.left);
            }
            if(cur.right != null) {
                que.push(cur.right)
            }
        }
      	// 每一层遍历之后的结果加入,result中
        result.push(level);
    }
    return result;
}
module.exports = {
    levelOrder : levelOrder
};