congr / world

2 stars 1 forks source link

Hackerrank : Tree : Top View #439

Closed congr closed 5 years ago

congr commented 5 years ago

https://www.hackerrank.com/challenges/tree-top-view/problem?isFullScreen=false

image image

congr commented 5 years ago
    static class TNode {
        int level;
        Node node;
        TNode(int level, Node node) {
            this.level = level;
            this.node = node;
        }
    }
    public static void topView(Node root) {
        Queue<TNode> q = new LinkedList();
        q.add(new TNode(0, root));

        TreeMap<Integer, Integer> map = new TreeMap();
        while(!q.isEmpty()) {
            TNode t = q.remove();
            if (!map.containsKey(t.level)) map.put(t.level, t.node.data);

            if (t.node.left != null) q.add(new TNode(t.level-1, t.node.left));
            if (t.node.right != null) q.add(new TNode(t.level+1, t.node.right));
        }

        for (int i : map.values()) {
            System.out.print(i + " ");
        }
    }
congr commented 5 years ago

image