Tree : Top View Hackerrank Solution
for explanation watch Video :
Code:
import java.util.*;
import java.io.*;
class Node {
Node left;
Node right;
int data;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
class Solution {
/*
class Node
int data;
Node left;
Node right;
*/
static class NodeLevel{
Node node;
Integer level;
NodeLevel(Node node,Integer level){
this.node = node;
this.level = level;
}
}
public static void topView(Node root) {
Queue<NodeLevel> q = new LinkedList<>();
TreeMap<Integer,Integer> tm = new TreeMap<>();
if(root==null){
return;
}
q.add(new NodeLevel(root,0));
while(!q.isEmpty()){
NodeLevel temp = q.poll();
Node temp1 = temp.node;
Integer level = temp.level;
if(!tm.containsKey(level)){
tm.put(level,temp1.data);
}
if(temp1.left!=null){
q.add(new NodeLevel(temp1.left,level-1));
}
if(temp1.right!=null){
q.add(new NodeLevel(temp1.right,level+1));
}
}
for(Map.Entry<Integer,Integer> e : tm.entrySet()){
System.out.print(e.getValue()+ " ");
}
}
public static Node insert(Node root, int data) {
if(root == null) {
return new Node(data);
} else {
Node cur;
if(data <= root.data) {
cur = insert(root.left, data);
root.left = cur;
} else {
cur = insert(root.right, data);
root.right = cur;
}
return root;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
Node root = null;
while(t-- > 0) {
int data = scan.nextInt();
root = insert(root, data);
}
scan.close();
topView(root);
}
Comments
Post a Comment