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]
题意:找出二叉树一层的最大值
解法:用BFS的方式遍历每一层
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
if not root:
return result
queue = [root]
while queue:
count = len(queue)
res = -2147483648
for i in range(count):
curNode = queue.pop(0)
res = max(curNode.val, res)
if curNode.left:
queue.append(curNode.left)
if curNode.right:
queue.append(curNode.right)
result.append(res)
return result
时间: 2024-11-10 02:22:32