Skip to content

Instantly share code, notes, and snippets.

@amraks
Created February 16, 2019 18:39
Show Gist options
  • Save amraks/c780a6a0b56519401a29353db022749c to your computer and use it in GitHub Desktop.
Save amraks/c780a6a0b56519401a29353db022749c to your computer and use it in GitHub Desktop.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: 'TreeNode') -> 'List[List[int]]':
if not root:
return []
q = [(root, 0)]
r = {}
i = 0
while q:
n, l = q.pop()
if l in r:
r[l].append(n.val)
else:
r[l] = [n.val]
if n.right:
q.append((n.right, l+1))
if n.left:
q.append((n.left, l+1))
a = list(r.values())
a.reverse()
return a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment