pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.38k stars 242 forks source link

二叉树的锯齿形层次遍历 #1066

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

103. 二叉树的锯齿形层次遍历

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function(root) {
    if(!root)
        return [];
    const queue = [root],
        nodes = [];
    let depth = 0;
    while(queue.length > 0) {
        let len = queue.length;
        if(!nodes[depth]) {
            nodes[depth] = [];
        }
        if(depth % 2 == 0) {
            //从左往右
            for(let i=0; i<len; i++) {
                nodes[depth].push(queue[i].val);
            }
        }else {
            //从右往左
            for(let i=len-1; i>=0; i--) {
                nodes[depth].push(queue[i].val);
            }
        }

        for(let i=0; i<len; i++) {
            queue[i].left && queue.push(queue[i].left);
            queue[i].right && queue.push(queue[i].right);
        }
        queue.splice(0, len);
        depth++;
    }
    return nodes;
};