给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其层序遍历结果:
[
[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) {
//层序遍历就是广度遍历
// if(!root){return 0;}
// const stack=[root]
// while(stack.length){
// const n=stack.shift()
// console.log(n.val)
// if(n.left) stack.push(n.left)
// if(n.right) stack.push(n.right)
// }
if(!root) return []
const stack=[[root,0]]
//用res来保存结果值
let res=[]
while(stack.length){
const [n,l]=stack.shift()
//如果当前级没有这层级的
if(!res[l]){
res.push([n.val])
}else{
res[l].push(n.val)
}
if(n.left) stack.push([n.left,l+1])
if(n.right) stack.push([n.right,l+1])
}
return res
};