-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
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
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 |