您需要在二叉树的每一行中找到最大的值。
示例:
输入: 1 / \ 3 2 / \ \ 5 3 9 输出: [1, 3, 9]
思路:按行搜索,也就是按层次进行搜索,使用BFS。
# 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]
"""
if not root:
return []
res = []
nodeList = [root]
while nodeList:
nodeTemp = []
nodeNext = []
for i in nodeList:
nodeTemp.append(i.val)
if i.left:
nodeNext.append(i.left)
if i.right:
nodeNext.append(i.right)
res.append(max(nodeTemp))
nodeList = nodeNext
return res