Spiral/Zigzag level order traversal of binary tree in java

ghz 10months ago ⋅ 115 views

To perform a spiral (or zigzag) level order traversal of a binary tree in Java, you can use a queue along with a stack to alternate between levels. Here's the implementation:

import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    
    public TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

public class SpiralLevelOrderTraversal {
    public static void main(String[] args) {
        // Example binary tree
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        
        System.out.println("Spiral (Zigzag) level order traversal:");
        spiralLevelOrderTraversal(root);
    }
    
    public static void spiralLevelOrderTraversal(TreeNode root) {
        if (root == null) return;
        
        Queue<TreeNode> queue = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        boolean reverse = false; // To alternate between levels
        
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                
                if (reverse) {
                    stack.push(node); // Push node to stack for reverse order
                } else {
                    System.out.print(node.val + " "); // Print node value for normal order
                }
                
                // Enqueue child nodes
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            
            // Print nodes from stack for reverse order
            while (!stack.isEmpty()) {
                System.out.print(stack.pop().val + " ");
            }
            
            reverse = !reverse; // Alternate between levels
        }
    }
}

This program performs a spiral (zigzag) level order traversal of a binary tree. It uses a queue to traverse the tree level by level and a stack to alternate between printing nodes in normal and reverse order.