|
| 1 | +package com.thealgorithms.datastructures.trees; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Given a binary tree. |
| 7 | + * This code returns the zigzag level order traversal of its nodes' values. |
| 8 | + * Binary tree: |
| 9 | + * 7 |
| 10 | + * / \ |
| 11 | + * 6 3 |
| 12 | + * / \ / \ |
| 13 | + * 2 4 10 19 |
| 14 | + * Zigzag traversal: |
| 15 | + * [[7], [3, 6], [2, 4, 10, 19]] |
| 16 | + * <p> |
| 17 | + * This solution implements the breadth-first search (BFS) algorithm using a queue. |
| 18 | + * 1. The algorithm starts with a root node. This node is added to a queue. |
| 19 | + * 2. While the queue is not empty: |
| 20 | + * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes at the current level. |
| 21 | + * - we traverse all the level nodes in 2 ways: from left to right OR from right to left |
| 22 | + * (this state is stored on `prevLevelFromLeftToRight` variable) |
| 23 | + * - if the current node has children we add them to a queue |
| 24 | + * - add level with nodes to a result. |
| 25 | + * <p> |
| 26 | + * Complexities: |
| 27 | + * O(N) - time, where N is the number of nodes in a binary tree |
| 28 | + * O(N) - space, where N is the number of nodes in a binary tree |
| 29 | + * |
| 30 | + * @author Albina Gimaletdinova on 11/01/2023 |
| 31 | + */ |
| 32 | +public class ZigzagTraversal { |
| 33 | + public static List<List<Integer>> traverse(BinaryTree.Node root) { |
| 34 | + if (root == null) { |
| 35 | + return new ArrayList<>(); |
| 36 | + } |
| 37 | + |
| 38 | + List<List<Integer>> result = new ArrayList<>(); |
| 39 | + |
| 40 | + // create a queue |
| 41 | + Deque<BinaryTree.Node> q = new ArrayDeque<>(); |
| 42 | + q.offer(root); |
| 43 | + // start with writing nodes from left to right |
| 44 | + boolean prevLevelFromLeftToRight = false; |
| 45 | + |
| 46 | + while (!q.isEmpty()) { |
| 47 | + int nodesOnLevel = q.size(); |
| 48 | + List<Integer> level = new LinkedList<>(); |
| 49 | + // traverse all the level nodes |
| 50 | + for (int i = 0; i < nodesOnLevel; i++) { |
| 51 | + BinaryTree.Node node = q.poll(); |
| 52 | + if (prevLevelFromLeftToRight) { |
| 53 | + level.add(0, node.data); |
| 54 | + } else { |
| 55 | + level.add(node.data); |
| 56 | + } |
| 57 | + if (node.left != null) { |
| 58 | + q.offer(node.left); |
| 59 | + } |
| 60 | + if (node.right != null) { |
| 61 | + q.offer(node.right); |
| 62 | + } |
| 63 | + } |
| 64 | + // the next level node traversal will be from the other side |
| 65 | + prevLevelFromLeftToRight = !prevLevelFromLeftToRight; |
| 66 | + result.add(level); |
| 67 | + } |
| 68 | + return result; |
| 69 | + } |
| 70 | +} |
0 commit comments