MCPcopy Index your code
hub / github.com/Tiwarishashwat/InterviewCodes / topView

Method topView

TreeTopView.java:15–56  ·  view source on GitHub ↗
(Node root)

Source from the content-addressed store, hash-verified

13 //Function to return a list of nodes visible from the top view
14 //from left to right in Binary Tree.
15 static ArrayList<Integer> topView(Node root)
16 {
17 // add your code
18 TreeMap<Integer,Integer> map = new TreeMap<>();
19
20 ArrayList<Integer> list = new ArrayList<>();
21
22 if(root==null) return list;
23
24 Queue<Pair> q = new LinkedList<>();
25
26 q.add(new Pair(root,0));
27
28 while(!q.isEmpty())
29 {
30 Pair p = q.remove();
31
32 int v = p.vertical;
33
34 Node node = p.node;
35
36 if(map.get(v)==null)
37 {
38 map.put(v,node.data);
39 }
40
41 if(node.left!=null)
42 {
43 q.add(new Pair(node.left,v-1));
44 }
45
46 if(node.right!=null)
47 {
48 q.add(new Pair(node.right,v+1));
49 }
50 }
51 for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
52 list.add(entry.getValue());
53 }
54 return list;
55
56 }
57
58}

Callers

nothing calls this directly

Calls 3

getValueMethod · 0.80
addMethod · 0.45
isEmptyMethod · 0.45

Tested by

no test coverage detected