Binary Tree Zigzag Level Order Traversal
Explore how to traverse a binary tree in zigzag level order by alternating left-to-right and right-to-left directions at each level. Understand the application of breadth-first search in this pattern to effectively solve coding interview problems involving tree traversal.
We'll cover the following...
Statement
Given a binary tree, return its zigzag level order traversal. The zigzag level order traversal corresponds to traversing nodes from left to right for one level, and then right to left for the next level, and so on, reversing direction after every level.
Constraints:
-
The number of nodes in the tree is in the range to .
-
node.data
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Binary Tree Zigzag Level Order Traversal
What will be the zigzag level order traversal of the following tree?
[0, 2, 4, 1, NULL, 3, -1, 5, 1, NULL, 6, NULL, 8]
[[0], [2, 4] , [1, NULL, 3, -1], [5, 1, NULL, 6, NULL, 8]]
[[0], [4, 2], [1, 3, -1], [8, 6, 1, 5]]
[0, 4, 2, 1, 3, -1, 8, 6, 1, 5]
[NULL]
Figure it out!
Here’s a game for you to play! Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in ZigZagLevelOrderTraversal.cpp in the coding playground below. We’ve provided some useful code templates in the other file that you may build on and use to solve this problem.
typedef TreeNode<int>* NodePtr;vector<vector<int>> ZigzagLevelOrder(TreeNode<int>* root){// Replace this placeholder return statement with your codereturn {};}