Binary Tree Level Order Traversal
二叉树层序遍历
- 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]
]
- BFS方法
var levelOrder = function(root) {
if(!root) return[]
const stack =[root]
const res = []
while(stack.length){
const len = stack.length; // 每一层遍历完,会重新赋值下次层的长度
const temp = [] // 存储每一层的值
// 删完一层的值,跳出for循环
//while判断下层还有值,取下一层长度,继续for循环遍历
for(let i = 0; i < len; i++){
const node = stack.shift()
temp.push(node.val)
if(node.left) stack.push(node.left)
if(node.right) stack.push(node.right)
}
res.push(temp)
}
return res
};