-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path650.find-leaves-of-binary-tree.py
94 lines (84 loc) · 2.09 KB
/
650.find-leaves-of-binary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# Tag: Binary Tree, Depth First Search/DFS, Divide and Conquer
# Time: O(N)
# Space: O(N)
# Ref: Leetcode-366
# Note: -
# 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.
#
# **Example1**
# Input: {1,2,3,4,5}
# Output: `[[4, 5, 3], [2], [1]]`.
# Explanation:
# ```
# 1
# / \
# 2 3
# / \
# 4 5
# ```
#
# **Example2**
# Input: {1,2,3,4}
# Output: `[[4, 3], [2], [1]]`.
# Explanation:
# ```
# 1
# / \
# 2 3
# /
# 4
# ```
#
#
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from collections import defaultdict
class Solution:
"""
@param: root: the root of binary tree
@return: collect and remove all leaves
"""
def findLeaves(self, root):
# write your code here
cache = defaultdict(list)
self.findReverseHeight(root, cache)
res = []
height = 0
while height in cache:
res.append(cache[height])
height += 1
return res
def findReverseHeight(self, root, cache):
if root is None:
return -1
lh = self.findReverseHeight(root.left, cache)
rh = self.findReverseHeight(root.right, cache)
height = max(lh, rh) + 1
cache[height].append(root.val)
return height
from collections import defaultdict
class Solution:
"""
@param: root: the root of binary tree
@return: collect and remove all leaves
"""
def findLeaves(self, root):
# write your code here
res = []
self.findReverseHeight(root, res)
return res
def findReverseHeight(self, root, res):
if root is None:
return -1
lh = self.findReverseHeight(root.left, res)
rh = self.findReverseHeight(root.right, res)
height = max(lh, rh) + 1
if height >= len(res):
res.append([])
res[height].append(root.val)
return height