Created
August 7, 2020 19:40
-
-
Save Daksh/8556a814c8489b9b5695398258781358 to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal II
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
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