forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-largest-value-in-each-tree-row.py
59 lines (52 loc) · 1.37 KB
/
find-largest-value-in-each-tree-row.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
# Time: O(n)
# Space: O(h)
# You need to find the largest value in each row of a binary tree.
#
# Example:
# Input:
#
# 1
# / \
# 3 2
# / \ \
# 5 3 9
#
# Output: [1, 3, 9]
# 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 largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def largestValuesHelper(root, depth, result):
if not root:
return
if depth == len(result):
result.append(root.val)
else:
result[depth] = max(result[depth], root.val)
largestValuesHelper(root.left, depth+1, result)
largestValuesHelper(root.right, depth+1, result)
result = []
largestValuesHelper(root, 0, result)
return result
# Time: O(n)
# Space: O(n)
class Solution2(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
curr = [root]
while any(curr):
result.append(max(node.val for node in curr))
curr = [child for node in curr for child in (node.left, node.right) if child]
return result