Practice › Trees
Zigzag Level Order Traversal
Medium · Trees · Asked at Amazon, Microsoft, Meta, Flipkart
Print the level order traversal in zigzag order: the first level left to right, the next right to left, and so on alternating. Print each level on its own line.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
One line per level.
Constraints
- 1 ≤ number of nodes ≤ 10^4
Do a normal BFS by levels and reverse every second level (or use a deque).
Example 1
Input
7 3 9 20 -1 -1 15 7
Output
3 20 9 15 7
Example 2
Input
7 1 2 3 4 5 6 7
Output
1 3 2 4 5 6 7
Hints
- Do a normal level-order traversal, one level at a time.
- Before printing a level, reverse it when the level number is odd.
Approach
BFS collects the values of each level left to right. Keep a flag that flips after every level; when it is set, print the level reversed. Reversing a list costs O(its length), so the total stays O(n).
Complexity: O(n) time · O(width) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// Build a tree from level order where -1 means "no node".
Node *readTree() {
int k;
cin >> k;
vector<long long> v(k);
for (auto &x : v) cin >> x;
if (k == 0 || v[0] == -1) return nullptr;
Node *root = new Node(v[0]);
queue<Node *> q;
q.push(root);
int i = 1;
while (!q.empty() && i < k) {
Node *cur = q.front();
q.pop();
if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
i++;
}
return root;
}
int main() {
Node *root = readTree();
queue<Node *> q;
q.push(root);
bool rev = false;
while (!q.empty()) {
int sz = q.size();
vector<long long> level;
for (int i = 0; i < sz; i++) {
Node *n = q.front();
q.pop();
level.push_back(n->val);
if (n->left) q.push(n->left);
if (n->right) q.push(n->right);
}
if (rev) reverse(level.begin(), level.end());
rev = !rev;
for (size_t i = 0; i < level.size(); i++) cout << level[i] << (i + 1 < level.size() ? " " : "\n");
}
return 0;
}Python solution
import sys
from collections import deque
sys.setrecursionlimit(100000)
class Node:
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build_tree(v):
"""Build a tree from level order where -1 means "no node"."""
if not v or v[0] == -1:
return None
root = Node(v[0])
q, i = deque([root]), 1
while q and i < len(v):
cur = q.popleft()
if i < len(v) and v[i] != -1:
cur.left = Node(v[i])
q.append(cur.left)
i += 1
if i < len(v) and v[i] != -1:
cur.right = Node(v[i])
q.append(cur.right)
i += 1
return root
data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build_tree(data[1 : 1 + k])
rest = data[1 + k :]
level, rev, out = [root], False, []
while level:
vals = [n.val for n in level]
out.append(" ".join(map(str, vals[::-1] if rev else vals)))
rev = not rev
level = [c for n in level for c in (n.left, n.right) if c]
print("\n".join(out))Java solution
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// Build a tree from level order where -1 means "no node".
static Node readTree(Scanner sc) {
int k = sc.nextInt();
long[] v = new long[k];
for (int i = 0; i < k; i++) v[i] = sc.nextLong();
if (k == 0 || v[0] == -1) return null;
Node root = new Node(v[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < k) {
Node cur = q.poll();
if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
i++;
}
return root;
}
public static void main(String[] args) {
Node root = readTree(new Scanner(System.in));
StringBuilder sb = new StringBuilder();
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
boolean rev = false;
while (!q.isEmpty()) {
int sz = q.size();
List<Long> level = new ArrayList<>();
for (int i = 0; i < sz; i++) {
Node n = q.poll();
level.add(n.val);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
if (rev) Collections.reverse(level);
rev = !rev;
for (int i = 0; i < level.size(); i++) sb.append(level.get(i)).append(i + 1 < level.size() ? " " : "\n");
}
System.out.print(sb);
}
}Solve Zigzag Level Order Traversal online · All practice problems