Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Example 2:
Input: root = [1,2,3]
Output: [1,3]
Constraints:
The number of nodes in the tree will be in the range [0, 104].
-231 <= Node.val <= 231 - 1
Solutions
Solution 1: BFS
We define a queue $q$ and put the root node into the queue. Each time, we take out all the nodes of the current level from the queue, find the maximum value, and then put all the nodes of the next level into the queue until the queue is empty.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 91011121314151617181920212223
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deflargestValues(self,root:Optional[TreeNode])->List[int]:ans=[]ifrootisNone:returnansq=deque([root])whileq:x=-inffor_inrange(len(q)):node=q.popleft()x=max(x,node.val)ifnode.left:q.append(node.left)ifnode.right:q.append(node.right)ans.append(x)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funclargestValues(root*TreeNode)(ans[]int){ifroot==nil{return}q:=[]*TreeNode{root}forlen(q)>0{x:=q[0].Valfori:=len(q);i>0;i--{node:=q[0]q=q[1:]x