|
1 | 1 | package binaryTree; |
| 2 | +import java.util.*; |
| 3 | +import java.util.Map.Entry; |
2 | 4 |
|
| 5 | +/* |
| 6 | + * Problem Title :- Write a Java program to find Top View of Tree. |
| 7 | + */ |
| 8 | +// Class of binary Tree |
3 | 9 | public class BT_Problem_11 { |
4 | 10 |
|
| 11 | + Node root; |
| 12 | + |
| 13 | + public BT_Problem_11() { |
| 14 | + root = null; |
| 15 | + } |
| 16 | + |
| 17 | + // function should print the topView of the binary tree |
| 18 | + private void TopView(Node root) { |
| 19 | + class QueueObj{ |
| 20 | + Node node; |
| 21 | + int hd; |
| 22 | + QueueObj(Node node, int hd){ |
| 23 | + this.node = node; |
| 24 | + this.hd = hd; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + Queue<QueueObj> q = new LinkedList<>(); |
| 29 | + Map<Integer, Node> topViewMap = new TreeMap<Integer, Node>(); |
| 30 | + |
| 31 | + if(root == null) |
| 32 | + return; |
| 33 | + else |
| 34 | + q.add(new QueueObj(root, 0)); |
| 35 | + |
| 36 | + System.out.println("The top view of the tree is : "); |
| 37 | + |
| 38 | + /* count function returns 1 if the container |
| 39 | + * contains an element whose key is equivalent to hd, |
| 40 | + * or returns zero otherwise. */ |
| 41 | + while(!q.isEmpty()) { |
| 42 | + QueueObj tempNode = q.poll(); |
| 43 | + |
| 44 | + if(!topViewMap.containsKey(tempNode.hd)) |
| 45 | + topViewMap.put(tempNode.hd, tempNode.node); |
| 46 | + |
| 47 | + if(tempNode.node.left != null) |
| 48 | + q.add(new QueueObj(tempNode.node.left, tempNode.hd + 1)); |
| 49 | + |
| 50 | + if(tempNode.node.left != null) |
| 51 | + q.add(new QueueObj(tempNode.node.left, tempNode.hd + 1)); |
| 52 | + } |
| 53 | + |
| 54 | + for(Entry<Integer, Node> entry : topViewMap.entrySet()) |
| 55 | + System.out.print(entry.getValue().data); |
| 56 | + } |
| 57 | + |
| 58 | + // Driver Program to test & run above functions |
5 | 59 | public static void main(String[] args) { |
6 | 60 |
|
| 61 | + BT_Problem_11 tree = new BT_Problem_11(); |
| 62 | + |
| 63 | + tree.root = new Node(1); |
| 64 | + tree.root.left = new Node(2); |
| 65 | + tree.root.right = new Node(3); |
| 66 | + tree.root.left.right = new Node(4); |
| 67 | + tree.root.left.right.right = new Node(4); |
| 68 | + tree.root.left.right.right.right = new Node(4); |
| 69 | + |
| 70 | + System.out.println("Following are nodes in top view of Binary Tree"); |
| 71 | + tree.TopView(tree.root); |
| 72 | + |
7 | 73 | } |
8 | 74 |
|
9 | 75 | } |
0 commit comments