-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0366-find-leaves-of-binary-tree.py
More file actions
40 lines (31 loc) · 1016 Bytes
/
0366-find-leaves-of-binary-tree.py
File metadata and controls
40 lines (31 loc) · 1016 Bytes
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
# time complexity: O(n)
# space complexity: O(n)
from collections import defaultdict
from typing import List, Optional
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: Optional[TreeNode]) -> List[List[int]]:
heightDict = defaultdict(list)
def getHeight(node):
if not node:
return -1
leftHeight = getHeight(node.left)
rightHeight = getHeight(node.right)
currHeight = max(leftHeight, rightHeight) + 1
heightDict[currHeight].append(node.val)
return currHeight
getHeight(root)
result = []
for value in heightDict.values():
result.append(value)
return result
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(Solution().findLeaves(root))