当前位置:网站首页>JS 力扣刷题 103. 二叉树的锯齿形层序遍历

JS 力扣刷题 103. 二叉树的锯齿形层序遍历

2022-04-23 13:54:00 Candy_Rainbow_

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;
};

版权声明
本文为[Candy_Rainbow_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Candy_Rainbow_/article/details/124361996