一、题目描述
二、解题思路
层序遍历。有多少层,res数组就有多长,遍历新的一层就要在对应res的位置初始化空数组,按层序遍历的顺序把节点值push进去。
三、代码实现
var levelOrder = function(root) {
let res = []
function bfs(root,depth){
if(root != null){
if(!res[depth]){
res[depth] = []
}
res[depth].push(root.val)
if(root.left){
bfs(root.left,depth+1)
}
if(root.right){
bfs(root.right,depth+1)
}
}
}
bfs(root,0)
return res
};