0
点赞
收藏
分享

微信扫一扫

JS 力扣刷题 107. 二叉树的层序遍历 II

大沈投资笔记 2022-04-25 阅读 77
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();//反转
};
举报

相关推荐

0 条评论