var levelOrderBottom = function(root) {
if(!root)return [];//特殊情况
const q = [[root, 0]];//层次遍历,记录每个节点和所在的层数
const res = [];
while(q.length){//队列层次遍历
[node, index] = q.shift();//出队
if(!res[index]){//该层第一个节点
res.push([node.val]);
}else{//该层其他节点
res[index].push(node.val);
}
if(node.left)q.push([node.left, index + 1]);
if(node.right)q.push([node.right, index + 1]);
}
return res.reverse();//反转
};
JS 力扣刷题 107. 二叉树的层序遍历 II
最新推荐文章于 2024-05-08 20:54:14 发布