var zigzagLevelOrder = function(root) {
let rear = [];//遍历的队列
let answers = [];//二维数组
if(!root)return answers;//特殊情况
rear.push(root);//根节点入队
let flagStack = 1;//单层从左往右(队列)双层从右往左(栈)
while(rear.length > 0){
let answer = [];//一层一层遍历
let len = rear.length;//队列长度会变,记录以下
for(let i = 0; i < len; i++){
let tmp = rear.shift();
if(flagStack % 2 == 1)//单层从左往右(队列)
answer.push(tmp.val);
else//双层从右往左(栈)
answer.unshift(tmp.val);
if(tmp.left)rear.push(tmp.left);
if(tmp.right)rear.push(tmp.right);
}
answers.push(answer);
flagStack++;
}
return answers;
};
|