Bottom view of BT
unknown
java
15 days ago
1.4 kB
6
Indexable
class Solution { class Pair { public int index; public Node value; public Pair(int i, Node v) { this.index = i; this.value = v; } } public void levelOrder(Node root, HashMap<Integer, Integer> map) { Queue<Pair> queue = new LinkedList<>(); queue.add(new Pair(0, root)); queue.add(new Pair(0, null)); int i; while (!queue.isEmpty()) { if (queue.peek().value == null) { queue.remove(); if (queue.isEmpty()) break; queue.add(new Pair(0, null)); } else { i = queue.peek().index; map.put(i, queue.peek().value.data); Pair temp = queue.remove(); if (temp.value.left != null) queue.add(new Pair(i - 1, temp.value.left)); if (temp.value.right != null) queue.add(new Pair(i + 1, temp.value.right)); } } } public ArrayList <Integer> bottomView(Node root) { ArrayList<Integer> list = new ArrayList<>(); HashMap<Integer, Integer> map = new HashMap<>(); if (root != null) levelOrder(root, map); PriorityQueue<Integer> pq = new PriorityQueue<>(map.keySet()); while(!pq.isEmpty()) { list.add(map.get(pq.remove())); } return list; } }
Editor is loading...
Leave a Comment