diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..92b0407c --- /dev/null +++ b/problem1.py @@ -0,0 +1,24 @@ +# problem 1 + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + self.result = [] + self.helper(root,0) + return self.result + + def helper(self,root,depth): + if not root: + return + + if len(self.result) == depth: + self.result.append([]) + + self.helper(root.left,depth+1) + self.result[depth].append(root.val) + self.helper(root.right,depth+1) \ No newline at end of file diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..f5d54dd5 --- /dev/null +++ b/problem2.py @@ -0,0 +1,38 @@ +# problem 2 + +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: + course_count = [0]*numCourses + my_graph = {} + + for prerequisite in prerequisites: + course_count[prerequisite[0]] +=1 + if prerequisite[1] not in my_graph: + my_graph[prerequisite[1]]= [] + my_graph[prerequisite[1]].append(prerequisite[0]) + + check_queue = deque() + count = 0 + for i in range(numCourses): + if course_count[i] == 0: + check_queue.append(i) + count+=1 + + + if not check_queue: + return False + if count == numCourses: + return True + + while(check_queue): + curr_class = check_queue.popleft() + graph_vals = my_graph.get(curr_class) + if graph_vals: + for graph_val in graph_vals: + course_count[graph_val] -=1 + if course_count[graph_val] == 0: + count+=1 + check_queue.append(graph_val) + if count == numCourses: + return True + return False \ No newline at end of file