Zig Zag or Spiral Traversal

Binary Trees FAQs Medium
  • This problem, known as Zigzag Level Order Traversal or Breadth First Search level order traversal in binary trees, is extensively used in artificial intelligence and machine learning
  • It is primarily leveraged in decision tree algorithms, used for building classification models
  • Furthermore, it is a crucial part of navigation systems, where decisions are made at each node until the destination node is reached
  • Understanding this pattern can greatly improve the search or recommendation algorithms in various sectors including e-commerce, social media and more

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Examples:

Input : root = [1, 2, 3, null, 4, 8, 5]

Output : [ [1] , [3, 2], [4, 8, 5] ]

Explanation : So at root we move from left to right.

At next level we move in opposite direction i.e. from right to left.

At next level again reverse the traversal i.e. from left to right.


Input : root = [3, 9, 20, null, null, 15, 7]

Output : [ [3] , [20, 9], [15, 7] ]

Explanation : So at root we move from left to right.

At next level we move in opposite direction i.e. from right to left , from 20 to 9.

At next level again reverse the traversal i.e. from left to right, from 15 to 7.


Input : root = [5, 1, 2, 8, null, 4, 5, null, 6]

Constraints

  • 1 <= Number of Nodes <= 104
  • -103 <= Node.val <= 103

Hints

  • The Breadth-First Search (BFS) approach using a queue is optimal for level-order traversal.
  • An alternative DFS (preorder traversal) approach is possible but requires: Passing the current level index to determine the order dynamically. Storing values in a list of lists where odd levels are reversed before returning.

Company Tags

Bain & Company Zomato Shopify Siemens Healthineers Lyft KPMG Wayfair Snowflake Goldman Sachs Unity Technologies Electronic Arts Optum Splunk Chewy IBM Red Hat Swiggy Oracle Riot Games Mastercard Rakuten Square HCL Technologies Medtronic Zoho Google Microsoft Amazon Meta Apple Netflix Adobe