Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions BinaryTreeLevelOrderTraversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Time Complexity : O(n), where n is the number of nodes in the binary tree
# Space Complexity : O(w), where w is the maximum width of the binary tree
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach

from collections import deque
from typing import Optional, List

class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
def __init__(self):
self.queue = deque() # Intialize a queue to keep track of the nodes at each level
self.result = [] # Intialize a result list to store the values of nodes at each level

def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root: # If the root is None, return an empty list
return self.result
self.queue.append(root) # Add the root node to the queue to start the level order traversal

while len(self.queue) > 0: # While there are nodes in the queue, continue the traversal
size = len(self.queue) # Get the number of nodes at the current level (size of the queue)
res=[] # Initialize a list to store the values of nodes at the current level
for i in range(size): # Iterate through the nodes at the current level
curr = self.queue.popleft() # Remove the current node from the queue
print(curr.val)
if curr.left is not None: # If the left child of the current node is not None, add it to the queue
self.queue.append(curr.left)
if curr.right is not None: # If the right child of the current node is not None, add it to the queue
self.queue.append(curr.right)
res.append(curr.val) # Add the value of the current node to the res list for the current level
self.result.append(res) # After processing all nodes at the current level, add the res list to the result list

return self.result # Return the final result list containing the values of nodes at each level

if __name__ == "__main__":
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)

sol = Solution()
print(sol.levelOrder(root))
50 changes: 50 additions & 0 deletions CourseSchedule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Time Complexity : O(V+E), where V is the number of courses/Vertices and E is the number of dependencies/Edges
# Space Complexity : O(V+E), where V is the number of courses/Vertices and E is the number of dependencies/Edges
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No


# Your code here along with comments explaining your approach

from collections import deque
from typing import List

class Solution:

def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
q = deque() # Initializing queue
indegrees = [0] * numCourses # Intiailizing indegrees array to store count of dependent on particular index/course
adjajency = {} # Adjajency hashmap to store Indexpendent course as key and list of dependent course as value to access faster
count = 0 # initializing count which would be incremented when a course has been satisfied

for pair in prerequisites: # Iterating the list of tuples
dep = pair[0] # first course is dependent
indep = pair[1] # second course is independent

indegrees[dep] += 1 # increasing the count of dependencies on each course

if indep not in adjajency:
adjajency[indep] = []

adjajency[indep].append(dep) # Adding the dependent course to its independent course

for idx, num in enumerate(indegrees): # storing courses with 0 dependencies in q and increasing count
if num == 0:
q.append(idx)
count += 1

while len(q): # If any course with 0 dependencies present, otherwise skip
curr = q.pop()
if curr not in adjajency: # Handling Null if no dependency on any course
continue
dep_list = adjajency[curr]
for num in dep_list:
indegrees[num] -= 1 # Reducing the dependency of that course OR completing pre req
if indegrees[num] == 0:
q.append(num)
count += 1

if count == numCourses: # At the end if count is equal to nuCourses, it means we can complete all the courses
return True

return False