LeetCode #515 Find Largest Value in Each Tree Row

Problem

You need to find the largest value in each row of a binary tree.

Example

1
2
3
4
5
6
7
8
9
Input: 

1
/ \
3 2
/ \ \
5 3 9

Output: [1, 3, 9]

Solution1

Method: Breadth-first Search

Time Complexity: O(n)

Space Complexity:

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []

ret = []
dq = collections.deque([(root, 0)])
row_maximum = [float('-inf'), 0]

while dq:
node, level = dq.popleft()
if not node:
continue
if level == row_maximum[1]:
row_maximum[0] = max(node.val, row_maximum[0])
else:
ret.append(row_maximum[0])
row_maximum = [node.val, level]
dq.append((node.left, level + 1))
dq.append((node.right, level + 1))

ret.append(row_maximum[0])
return ret

Solution2

Method: Depth-first Search

Time Complexity: O(n)

Space Complexity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
bag = [(root, 1)]

while bag:
node, level = bag.pop()
if not node:
continue

if level > len(ret):
ret.append(node.val)
else:
if ret[level - 1] < node.val:
ret[level - 1] = node.val

bag.append((node.right, level + 1))
bag.append((node.left, level + 1))

return ret