You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSolution(object):
deflevelOrder(self, root):
""" :type root: TreeNode :rtype: List[List[int]] -> [[3],[9,20],[15,7]] """result= []
ifroot:
bfs_queue= [[root]]
whilelen(bfs_queue) >0:
cur_level=bfs_queue.pop(0) # dequeresult.append([node.valfornodeincur_level])
next_level= []
# add all the children of the node in the cur level in the queuefornodeincur_level:
ifnode.left:
next_level.append(node.left)
ifnode.right:
next_level.append(node.right)
bfs_queue.append(next_level)
iflen(next_level) ==0:
breakreturnresult
3.1. BFS for Graph
BFS for Graph: need to keep track on visited = set() vertices
BFS to find shortest path for un-weighted graph or weighted graph if all costs are equal, we can use BFS (Level Traversal) instead of Dijkstra's algorithm.
Find Neighbors:
2D Matrix:
direction= [(0,-1), (0,1), (-1,0), (1,0)] #Top, Down, Left, Rightwhile(queue):
i, j=queue.pop(0)
ford_i, d_jindirection:
new_i, new_j=i+d_i, j+d_jif (new_i>=0andnew_i<row) and (new_j>=0andnew_j<col):
#For valid new_i, new_j, do something