Categories
Binary Tree Breadth First Search

Level Order ZigZag Traversal

function levelOrderZigzag(root) {

    let queue = [root], result = [], direction = 0;
    function process(node) {
        result.push(node.val); //?
    }

    while (queue.length) {
        let level = [];
        while(queue.length) {
            const node = queue.pop();
            process(node);
            if (direction === 0) {
                if (node.left) level.push(node.left);
                if (node.right) level.push(node.right);
            }
            else {
                if (node.right) level.push(node.right);
                if (node.left) level.push(node.left);
            }
        }
        direction ^= 1;
        queue = level;
    }

    return result; //?
}

Leave a Reply

Your email address will not be published. Required fields are marked *