Search⌘ K

Binary Tree Zigzag Level Order Traversal

Explore the technique of zigzag level order traversal in binary trees using JavaScript. Understand how to modify breadth-first search with a deque to alternate node order per level. This lesson teaches you to traverse and store nodes in a zigzag pattern, useful for coding interviews focused on tree data structures.

Description

Given a binary tree T, you have to find its nodes’ zigzag level order traversal. The zigzag level order traversal corresponds to traversing nodes from left to right and then right to left for the next level, alternating between.

You have to return the elements in each level in a two-dimensional array.

Let’s look at an example:

Coding exercise

Javascript (babel-node)
import {TreeNode} from './TreeNode.js'
function zigzagLevelOrder(root){
}
Binary Tree Zigzag Level Order Traversal

Solution

As per the problem statement, we need to traverse the tree in a level-by-level zigzag order. An intuitive approach for this problem would be to use Breadth-First Search (BFS). By default, BFS provides ordering from left to right within a single level.

We will need to modify BFS a little to get our desired output, a zigzagzigzag ...