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

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刷题,队列,leetcode,javascript)