102. Binary Tree Level Order Traversal(js)

102. Binary Tree Level Order Traversal

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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
题意:二叉搜索树的层序遍历,存入二维数组中
代码如下:
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    let res=[];
    
    if(!root) return res;
    let q=[];
    q.push(root);
    while(q.length>0){
        let level=[];
        let size=q.length;
        for(let i=0;i<size;i++){
            let node=q.shift();
            level.push(node.val);
            if(node.left) q.push(node.left);
            if(node.right) q.push(node.right);
        }
        res.push(level);
    }
    return res;
};

 

posted @ 2019-04-15 20:47  mingL  阅读(88)  评论(0编辑  收藏  举报