|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | + |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +public class _863 { |
| 8 | + public static class Solution1 { |
| 9 | + /** |
| 10 | + * Since it's asking for distance k, a.k.a shortest distance, BFS should be the way to go. |
| 11 | + * For this particular problem: we'll do BFS twice: |
| 12 | + * 1st time: we build a child to parent mapping, in binary tree, there's only parent to children mapping, so we'll need to establish this child to parent link; |
| 13 | + * 2nd time: we push the target node into the queue, traverse all its neighbors (children and parent), |
| 14 | + * push them into the queue and decrement k by one, until k becomes zero, remaining elements in the queue are the answer. |
| 15 | + */ |
| 16 | + public List<Integer> distanceK(TreeNode root, TreeNode target, int k) { |
| 17 | + Map<Integer, TreeNode> childToParentMap = new HashMap<>(); |
| 18 | + Queue<TreeNode> queue = new LinkedList<>(); |
| 19 | + queue.offer(root); |
| 20 | + while (!queue.isEmpty()) { |
| 21 | + int size = queue.size(); |
| 22 | + for (int i = 0; i < size; i++) { |
| 23 | + TreeNode curr = queue.poll(); |
| 24 | + if (curr.left != null) { |
| 25 | + childToParentMap.put(curr.left.val, curr); |
| 26 | + queue.offer(curr.left); |
| 27 | + } |
| 28 | + if (curr.right != null) { |
| 29 | + childToParentMap.put(curr.right.val, curr); |
| 30 | + queue.offer(curr.right); |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + queue.offer(target); |
| 35 | + Set<Integer> visited = new HashSet<>(); |
| 36 | + while (k > 0 && !queue.isEmpty()) { |
| 37 | + int size = queue.size(); |
| 38 | + for (int i = 0; i < size; i++) { |
| 39 | + TreeNode curr = queue.poll(); |
| 40 | + visited.add(curr.val); |
| 41 | + if (curr.left != null && !visited.contains(curr.left.val)) { |
| 42 | + queue.offer(curr.left); |
| 43 | + } |
| 44 | + if (curr.right != null && !visited.contains(curr.right.val)) { |
| 45 | + queue.offer(curr.right); |
| 46 | + } |
| 47 | + if (childToParentMap.containsKey(curr.val) && !visited.contains(childToParentMap.get(curr.val).val)) { |
| 48 | + queue.offer(childToParentMap.get(curr.val)); |
| 49 | + } |
| 50 | + } |
| 51 | + k--; |
| 52 | + } |
| 53 | + List<Integer> list = new ArrayList<>(); |
| 54 | + while (!queue.isEmpty()) { |
| 55 | + list.add(queue.poll().val); |
| 56 | + } |
| 57 | + return list; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments