var levelOrder = function(root) {
let rear = [];//遍历的队列
let answers = [];//二维数组
if(!root)return answers;//特殊情况
rear.push(root);//根节点入队
while(rear.length > 0){
let answer = [];//一层一层遍历
let len = rear.length;//队列长度会变,记录以下
for(let i = 0; i < len; i++){
let tmp = rear.shift();
answer.push(tmp.val);
if(tmp.left)rear.push(tmp.left);
if(tmp.right)rear.push(tmp.right);
}
answers.push(answer);
}
return answers;
};
JS 力扣刷题 102. 二叉树的层序遍历
最新推荐文章于 2024-08-15 05:02:54 发布