import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".

class Node{
    int data;
    Node left,right;
    Node(int x) {
        data=x;
        left=right=null;
    }
}


class Main {
    public static Node createBinaryTree(int[] arr) {
        if (arr == null || arr.length == 0) return null;
    
        Node root = new Node(arr[0]);
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
    
        int i = 1;
        while (!queue.isEmpty() && i < arr.length) {
            Node current = queue.poll();
    
            if (i < arr.length && arr[i] != -1) {
                current.left = new Node(arr[i]);
                queue.add(current.left);
            }
            i++;
    
            if (i < arr.length && arr[i] != -1) {
                current.right = new Node(arr[i]);
                queue.add(current.right);
            }
            i++;
        }
    
        return root;
    }

    public static List<List<Integer>> verticalOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;

        Map<Integer, List<Integer>> map = new TreeMap<>();
        Queue<Pair> queue = new LinkedList<>();
        queue.add(new Pair(root, 0));

        while (!queue.isEmpty()) {
            Pair current = queue.poll();
            Node node = current.node;
            int hd = current.hd;

            if (!map.containsKey(hd)) {
                map.put(hd, new ArrayList<>());
            }
            map.get(hd).add(node.data);

            if (node.left != null) {
                queue.add(new Pair(node.left, hd - 1));
            }

            if (node.right != null) {
                queue.add(new Pair(node.right, hd + 1));
            }
        }

        // Convert map to list of lists
        for (List<Integer> list : map.values()) {
            result.add(list);
        }

        return result;
    }
    static class Pair {
        Node node;
        int hd;

        Pair(Node node, int hd) {
            this.node = node;
            this.hd = hd;
        }
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int arr[]=new int[n];
        for(int i=0;i<n;i++)
            arr[i]=sc.nextInt();

        Node root=createBinaryTree(arr);
        List<List<Integer>> verticalOrderTraversal = verticalOrder(root);
        for (List<Integer> level : verticalOrderTraversal) {
            System.out.println(level);
        }
    }
}

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: