- Notifications
You must be signed in to change notification settings - Fork24
Open
Labels
Description
队列 bfs
使用队列进行广度优先遍历,level 数组存放当前层级的值,处理完一层后推入结果数组 result。
constlevelOrder=function(root){if(root==null)return[]constresult=[]constqueue=[root]while(queue.length>0){constlevelSize=queue.lengthconstlevel=[]for(leti=0;i<levelSize;i++){consthead=queue.shift()for(constchildofhead.children){queue.push(child)}level.push(head.val)}result.push(level)}returnresult}
- 时间复杂度:O(n)
- 空间复杂度:O(n)