Created
July 21, 2020 04:04
-
-
Save jonathanagustin/cb25d63fa517b7055b955dc632772f13 to your computer and use it in GitHub Desktop.
Basic Recursive BFS
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
| # 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