Last active
January 17, 2022 12:46
-
-
Save Ian729/09a84f36d4149f0ca0e3cef8f8dd6562 to your computer and use it in GitHub Desktop.
Breadth First Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Leetcode 102 103 | |
# Breadth First Search Simplest | |
def bfs(root): | |
queue = [root] | |
while queue: | |
n = queue.pop(0) | |
queue.append(n.left) | |
queue.append(n.right) | |
# based on that, what we are deadling with might not be a perfect binary tree | |
# then what we can do is skip Null node | |
def bfs(root): | |
queue = [root] | |
while queue: | |
n = queue.pop(0) | |
if not n: | |
continue | |
queue.append(n.left) | |
queue.append(n.right) | |
# based on that, if we want to keep track of the level | |
# then what we can do is | |
def bfs(root): | |
queue = [ (root, 0) ] | |
while queue: | |
n, lvl = queue.pop(0) | |
if not n: | |
continue | |
queue.append( (n.left, lvl + 1) ) | |
queue.append( (n.right, lvl + 1) ) | |
# then we can think about the list we want to return | |
def bfs(root): | |
queue = [ (root, 0) ] | |
ret = [] | |
while queue: | |
n, lvl = queue.pop(0) | |
if not n: | |
continue | |
if len(ret) <= lvl: # when we meet the first element in a new layer | |
ret.append( [] ) | |
ret[lvl].append(n.val) | |
queue.append( (n.left, lvl + 1) ) | |
queue.append( (n.right, lvl + 1) ) | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment