-
Notifications
You must be signed in to change notification settings - Fork 43
/
find-leaves-of-binary-tree.py
107 lines (98 loc) · 2.95 KB
/
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
95
96
97
98
99
100
101
102
103
104
105
106
107
# V0
# V1
# https://blog.csdn.net/danspace1/article/details/87738403
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findLeaves(self, root: 'TreeNode') -> 'List[List[int]]':
def getLevel(root, d):
if not root:
return 0
left = getLevel(root.left, d)
right = getLevel(root.right, d)
level = 1 + max(left, right)
d[level].append(root.val)
return level
d = collections.defaultdict(list)
getLevel(root, d)
res = []
for k in sorted(d.keys()):
res.append(d[k])
return res
# V1'
# https://blog.csdn.net/danspace1/article/details/87738403
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
d = collections.defaultdict(list)
ans = []
def traverse(root):
# return the level of the nodes
if not root:
return 0
left = traverse(root.left)
right = traverse(root.right)
level = max(left, right) + 1
d[level].append(root.val)
return level
traverse(root)
for i in range(1, len(d)+1):
ans.append(d[i])
return ans
# V1''
# https://www.jiuzhang.com/solution/find-leaves-of-binary-tree/#tag-highlight-lang-python
class Solution:
"""
@param: root: the root of binary tree
@return: collect and remove all leaves
"""
def __init__(self):
self.leaves = []
def findLeaves(self, root):
# write your code here
self.tree_height(root)
return self.leaves
def tree_height(self, root):
if root == None:
return -1
left_height = self.tree_height(root.left)
right_height = self.tree_height(root.right)
height = 1 + max(left_height, right_height)
if height >= len(self.leaves):
self.leaves.append([])
self.leaves[height].append(root.val)
return height
# V2
# Time: O(n)
# Space: O(h)
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def findLeavesHelper(node, result):
if not node:
return -1
level = 1 + max(findLeavesHelper(node.left, result), \
findLeavesHelper(node.right, result))
if len(result) < level + 1:
result.append([])
result[level].append(node.val)
return level
result = []
findLeavesHelper(root, result)
return result