Skip to content

Commit

Permalink
366.py
Browse files Browse the repository at this point in the history
  • Loading branch information
224apps committed Dec 6, 2020
1 parent d3a6443 commit ce277be
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions 301-400/366.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
'''
Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: [[4,5,3],[2],[1]]
Explanation:
1. Removing the leaves [4,5,3] would result in this tree:
1
/
2
2. Now removing the leaf [2] would result in this tree:
1
3. Now removing the leaf [1] would result in the empty tree:
[]
[[3,5,4],[2],[1]], [[3,4,5],[2],[1]], etc, are also consider correct answers since per each level it doesn't matter the order on which elements are returned.
'''
# 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 findLeaves(self, root: TreeNode) -> List[List[int]]:


def getHeight(node):

if not node:
return -1
height = max(getHeight(node.left), getHeight(node.right)) + 1

if height == len(res):
res.append([])

res[height].append(node.val)
return height


res = []
getHeight(root)
return res

0 comments on commit ce277be

Please sign in to comment.