Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active March 25, 2024 03:47
Show Gist options
  • Save thmain/136b85436599ad901af7 to your computer and use it in GitHub Desktop.
Save thmain/136b85436599ad901af7 to your computer and use it in GitHub Desktop.
public class Main {
public static Map<Integer, Integer> ht = new HashMap<>();;
public static void topView(Node root, int level) {
if (root == null)
return;
Queue<QueuePack> queue = new LinkedList<>();
queue.add(new QueuePack(level, root));
while (!queue.isEmpty()) {
QueuePack q = queue.remove();
Node tnode = q.tnode;
int lvl = q.level;
// check if this is the first node you are visiting at the level
if (!ht.containsKey(lvl)) {
// print it, its the first element at his level
System.out.print(tnode.data + " ");
ht.put(lvl, tnode.data);
}
// add the left and right children of visiting nodes to the queue
if (tnode.left != null) {
queue.add(new QueuePack(lvl - 1, tnode.left));
}
if (tnode.right != null) {
queue.add(new QueuePack(lvl + 1, tnode.right));
}
}
}
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.left.left = new Node(8);
root.left.left.right = new Node(9);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
topView(root, 0);
}
}
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
left = null;
right = null;
}
}
// this class' represents the items stored in queue
class QueuePack {
int level;
Node tnode;
public QueuePack(int level, Node tnode) {
this.level = level;
this.tnode = tnode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment