• + 0 comments

    DFs:

    public static void top(Node root,Map m,int w,int h){

        if(root == null) return;
    
        if(!m.containsKey(w))  
            m.put(w, new int[]{h,root.data});
        else if(m.get(w)[0] > h)
            m.put(w, new int[]{h,root.data});
    
        top(root.left, m,w-1,h+1);
        top(root.right, m, w+1,h+1);
    

    }

    public static void topView(Node root) {

        Map<Integer,int[]> m = new TreeMap<Integer,int[]>();
        top(root,m,0,0);
        for(int k : m.keySet()){
            System.out.print(m.get(k)[1] + " ");
        }
    }