Java Binary Tree Top View with BFS and HashMap

🚀 Top View of a Binary Tree in Java | BFS + HashMap Approach Today I implemented an efficient solution to find the Top View of a Binary Tree using Java. This approach uses Breadth-First Search (BFS) along with a HashMap to track the first node encountered at each horizontal distance. 🔍 Key Concepts Used: Queue (BFS) to traverse level-wise HashMap to store the first node at each horizontal distance Tracking minimum and maximum distances to print the result in order 💡 Why this works: The first node encountered at each horizontal distance from the root represents the top view, and BFS ensures we visit nodes level by level. 🧠 Code Snippet: class Solution { class Pair{ Node node; int dist; Pair(Node node , int dist){ this.node = node; this.dist = dist; } } public ArrayList<Integer> topView(Node root) { ArrayList<Integer> ans = new ArrayList<>(); HashMap<Integer,Integer> mp = new HashMap<>(); Queue<Pair> q = new LinkedList<>(); q.add(new Pair(root,0)); int minDist = Integer.MAX_VALUE , maxDist = Integer.MIN_VALUE; while(!q.isEmpty()){ Pair front = q.remove(); Node node = front.node; int dist = front.dist; minDist = Math.min(minDist,dist); maxDist = Math.max(maxDist,dist); if(!mp.containsKey(dist)) mp.put(dist,node.data); if(node.left!=null) q.add(new Pair(node.left,dist-1)); if(node.right!=null) q.add(new Pair(node.right,dist+1)); } for(int i=minDist;i<=maxDist;i++){ ans.add(mp.get(i)); } return ans; } } 📌 Use Cases: Tree visualization problems Competitive programming Coding interviews 💬 Let me know if you’d like the bottom view, left view, or right view versions too! #Java #DataStructures #BinaryTree #Algorithms #Coding #BFS #InterviewPreparation #ComputerScience #DSA

To view or add a comment, sign in

Explore content categories