Created
June 3, 2020 00:40
-
-
Save liyunrui/3bb92941556d98073b83e11751e3e94e to your computer and use it in GitHub Desktop.
leetcode-binary tree
This file contains 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]: | |
""" | |
BFS for binary tree vs BFS for graph | |
1. without the need of visited array | |
2 the neighbor is left node and right node only. | |
T:O(n) | |
S:O(n) | |
""" | |
if root is None: | |
return [] | |
self.ans = [] | |
def bfs(root): | |
q = collections.deque([(root, 0)]) # (node, level) | |
while len(q) != 0: | |
cur_node, level = q.popleft() | |
if level == len(self.ans): | |
self.ans.append([]) | |
self.ans[level].append(cur_node.val) | |
l, r = cur_node.left, cur_node.right # neighbor | |
if l is not None: | |
q.append((l, level +1)) | |
if r is not None: | |
q.append((r, level +1)) | |
bfs(root) | |
return self.ans[::-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment