|
| 1 | +import java.util.Scanner; |
| 2 | +import java.util.Queue; |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.TreeMap; |
| 6 | + |
| 7 | +class BottomViewOfBTUsingDFS{ |
| 8 | + |
| 9 | + static class Node{ |
| 10 | + int val; |
| 11 | + Node right; |
| 12 | + Node left; |
| 13 | + Node(int val){ |
| 14 | + this.val = val; |
| 15 | + this.left = null; |
| 16 | + this.right = null; |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + static Node root; |
| 21 | + static Queue<Node> q = new LinkedList<>(); |
| 22 | + |
| 23 | + static void buildTree(int[] nodes){ |
| 24 | + if(nodes.length == 0) return; |
| 25 | + root = new Node(nodes[0]); |
| 26 | + q.add(root); |
| 27 | + int i = 1; |
| 28 | + |
| 29 | + while(!q.isEmpty()){ |
| 30 | + Node current = q.poll(); |
| 31 | + if(i<nodes.length && nodes[i] != -1){ |
| 32 | + if(current.left == null){ |
| 33 | + current.left = new Node(nodes[i++]); |
| 34 | + q.add(current.left); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if(i<nodes.length && nodes[i] != -1){ |
| 39 | + if(current.right == null){ |
| 40 | + current.right = new Node(nodes[i++]); |
| 41 | + q.add(current.right); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + static void bottomView(Node root){ |
| 48 | + Map<Integer, int[]> map = new TreeMap<>(); // {hd: [node.val, level]} |
| 49 | + dfs(root, map, 0, 0); |
| 50 | + System.out.print("Top view: "); |
| 51 | + for(int[] pairs : map.values()){ |
| 52 | + System.out.print(pairs[0] + " "); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + static void dfs(Node root, Map<Integer, int[]> map, int hd, int level){ |
| 57 | + if(root == null){ |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + if(!map.containsKey(hd) || map.get(hd)[1] <= level){ // we are checking the level value at the same hd in the map. |
| 62 | + //if the level value we are processing is >= than the one already in map, we will put in the map |
| 63 | + map.put(hd, new int[]{root.val, l}); |
| 64 | + } |
| 65 | + |
| 66 | + dfs(root.left, map, hd-1, level+1); |
| 67 | + dfs(root.right, map, hd+1, level+1); |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] args){ |
| 71 | + Scanner input = new Scanner(System.in); |
| 72 | + System.out.println("Enter the number of nodes: "); |
| 73 | + int n = input.nextInt(); |
| 74 | + int[] nodes = new int[n]; |
| 75 | + System.out.println("Enter the nodes: "); |
| 76 | + for(int i = 0; i<n; i++){ |
| 77 | + nodes[i] = input.nextInt(); |
| 78 | + } |
| 79 | + buildTree(nodes); |
| 80 | + bottomView(root); |
| 81 | + } |
| 82 | +} |
0 commit comments