|
| 1 | +/*-------------------------- |
| 2 | + Time Complexity: O(n) |
| 3 | + Space Complexity: O(n) |
| 4 | +---------------------------*/ |
| 5 | +class Solution { |
| 6 | + public int amountOfTime(TreeNode root, int start) { |
| 7 | + Map<Integer, List<Integer>> g = treeTograph(root); |
| 8 | + int time = 0; |
| 9 | + Queue<Integer> q = new LinkedList<>(); |
| 10 | + Set<Integer> visited = new HashSet<>(); |
| 11 | + q.add(start); |
| 12 | + visited.add(start); |
| 13 | + |
| 14 | + while(!q.isEmpty()){ |
| 15 | + int size = q.size(); |
| 16 | + for (int i = 0; i < size; i++) { |
| 17 | + int curr = q.poll(); |
| 18 | + for (int neighbour : g.get(curr)) { |
| 19 | + if (!visited.contains(neighbour)) { |
| 20 | + q.add(neighbour); |
| 21 | + visited.add(neighbour); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + time++; |
| 26 | + } |
| 27 | + return time-1; |
| 28 | + } |
| 29 | + public HashMap<Integer, List<Integer>> treeTograph(TreeNode root) { |
| 30 | + HashMap<Integer, List<Integer>> graph = new HashMap<>(); |
| 31 | + buildGraph(root, graph); |
| 32 | + return graph; |
| 33 | + } |
| 34 | + |
| 35 | + private void buildGraph(TreeNode node, HashMap<Integer, List<Integer>> graph) { |
| 36 | + if (node == null) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + graph.putIfAbsent(node.val, new ArrayList<>()); |
| 41 | + |
| 42 | + if (node.left != null) { |
| 43 | + graph.get(node.val).add(node.left.val); |
| 44 | + graph.putIfAbsent(node.left.val, new ArrayList<>()); |
| 45 | + graph.get(node.left.val).add(node.val); |
| 46 | + buildGraph(node.left, graph); |
| 47 | + } |
| 48 | + |
| 49 | + if (node.right != null) { |
| 50 | + graph.get(node.val).add(node.right.val); |
| 51 | + graph.putIfAbsent(node.right.val, new ArrayList<>()); |
| 52 | + graph.get(node.right.val).add(node.val); |
| 53 | + buildGraph(node.right, graph); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments