diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..5dd689ec --- /dev/null +++ b/Problem1.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/binary-tree-level-order-traversal/ +// Time Complexity : O(n) where n is the number of nodes in the tree. +// Space Complexity : O(h) where h is the height of the tree. +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +class Solution { + List> result = new LinkedList<>(); + public List> levelOrder(TreeNode root) { + if(root == null) return result; + dfs(root, 0); + return result; + } + + private void dfs(TreeNode root, int level){ + if(root == null) return; + if(result.size() == level){ + result.add(new ArrayList<>()); + } + dfs(root.left, level +1); + result.get(level).add(root.val); + dfs(root.right, level +1); + } +} \ No newline at end of file diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..ae7f6626 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,52 @@ +// https://leetcode.com/problems/course-schedule/ +// Time Complexity : O(V + E) where V is the number of courses and E is the number of prerequisites. +// Space Complexity : O(V + E) where V is the number of courses and E is the number of prerequisites. +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +class Solution { + public boolean canFinish(int numCourses, int[][] prerequisites) { + HashMap> aList = new HashMap<>(); + int[] indegrees = new int[numCourses]; + for (int[] pr : prerequisites) { + indegrees[pr[0]]++; + if (!aList.containsKey(pr[1])) { + aList.put(pr[1], new ArrayList()); + } + aList.get(pr[1]).add(pr[0]); + } + + Queue q = new LinkedList<>(); + int cnt = numCourses; + for (int i = 0; i < numCourses; i++) { + if (indegrees[i] == 0) { + q.add(i); + cnt--; + } + } + if (cnt == 0) + return true; + if (q.isEmpty()) + return false; + while (!q.isEmpty()) { + int curr = q.poll(); + List li = aList.get(curr); + if (li != null) { + for (int child : li) { + indegrees[child]--; + if (indegrees[child] == 0) { + q.add(child); + cnt--; + if (cnt == 0) { + return true; + } + } + } + } + } + if (cnt == 0) { + return true; + } + return false; + } +} \ No newline at end of file