算法- 二叉树层序遍历 - LeetCode:102.二叉树的层序遍历

35 阅读1分钟

image.png

二叉树层序遍历也就是广度优先遍历

var levelOrder = function(root) {
    let res=[];
    let stack=[];
    if(root!=null){
      stack.push(root);
    } 
    while(stack.length!==0){
       let size=stack.length;
       let cul=[];
       for(let i=0;i<size;i++){
         let node=stack.shift();
         cul.push(node.val);
         node.left&&stack.push(node.left);
         node.right&&stack.push(node.right);
        }
        res.push(cul);
    }
   return res;
};