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; //? }
Categories