515. 在每個樹行中找最大值
阿新 • • 發佈:2018-12-13
您需要在二叉樹的每一行中找到最大的值。
示例:
輸入: 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