Skip to content

Instantly share code, notes, and snippets.

@Daksh
Created August 7, 2020 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daksh/8556a814c8489b9b5695398258781358 to your computer and use it in GitHub Desktop.
Save Daksh/8556a814c8489b9b5695398258781358 to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal II
from collections import deque
# 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]]:
if not root:
return []
ans = []
subans = []
q = deque()
root.h = 0
q.appendleft(root)
while q:
e = q.pop()
if subans and subans[-1].h != e.h:
ans.insert(0,[el.val for el in subans])
subans = []
subans.append(e)
if e.left:
e.left.h = e.h + 1
q.appendleft(e.left)
if e.right:
e.right.h = e.h + 1
q.appendleft(e.right)
ans.insert(0,[el.val for el in subans])
return ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment