Untitled

 avatar
unknown
plain_text
a month ago
2.0 kB
1
Indexable
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
    public static class Node{
        int val;
        Node left;
        Node right;
        Node(int val){
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }
    public static class Info{
       int hd;
       Node node;
       Info(Node node , int hd){
           this.node = node;
           this.hd = hd;
       }
    }
    public static void topView(Node root){
        // Level Order 
        Queue<Info> q = new LinkedList<>();
        HashMap<Integer,Node> map = new HashMap<>();
        int min=0 , max =0;
        q.add(new Info(root , 0));
        q.add(null);
        
        while(!q.isEmpty()){
            //Null Check
            Info curr = q.remove();
            if(curr == null){
                if(q.isEmpty()){
                    break;
                } else {
                    q.add(null);
               
                }
                } else {
                if(!map.containsKey(curr.hd)){
                map.put(curr.hd,curr.node);
            }
            
            if(curr.node.left != null){
                q.add(new Info(curr.node.left , curr.hd-1));
                min = Math.min(min,curr.hd-1);
            }
            if(curr.node.right!=null){
                q.add(new Info(curr.node.right , curr.hd+1));
                max = Math.max(max,curr.hd+1);
            }
        }
            }
            
           
        for(int i = min ;i<=max;i++){
            System.out.print((map.get(i)).val +" ");
        }
    }
    public static void main(String[] args) {
      Node root = new Node(1);
      root.left = new Node(2);
      root.right = new Node(3);
      root.left.left = new Node(4);
      root.left.right = new Node(5);
      root.right.left = new Node(6);
      root.right.right = new Node(7);
      topView(root);
    }
}
Leave a Comment