题目描述:
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
题解:
1.解题思路:广度优先搜索
/**
* 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) {
const ret = [];
if(!root){
return ret;
}
const q = [];
q.push(root);
while(q.length!==0){
const currentLevelSize = q.length;
ret.push([]);
for(let i=0;i<=currentLevelSize-1;i++){
const node = q.shift();
ret[ret.length-1].push(node.val);
if(node.left) q.push(node.left);
if(node.right) q.push(node.right);
}
}
return ret;
};