Skip to content

Instantly share code, notes, and snippets.

@jonathanagustin
Created July 21, 2020 04:04
Show Gist options
  • Select an option

  • Save jonathanagustin/cb25d63fa517b7055b955dc632772f13 to your computer and use it in GitHub Desktop.

Select an option

Save jonathanagustin/cb25d63fa517b7055b955dc632772f13 to your computer and use it in GitHub Desktop.
Basic Recursive BFS
# 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: TreeNode) -> List[List[int]]:
levels = collections.defaultdict(list)
def bfs(node, level):
if node:
levels[level].append(node.val)
bfs(node.left, level+1)
bfs(node.right, level+1)
bfs(root, 0)
return levels.values()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment