---
# System prepended metadata

title: 0515. Find Largest Value in Each Tree Row
tags: [Leetcode, BFS, Medium]

---

# 0515. Find Largest Value in Each Tree Row
###### tags: `Leetcode` `BFS` `Medium`
Link: https://leetcode.com/problems/find-largest-value-in-each-tree-row/

## 思路
BFS

## Code
```java=
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        if(root == null) return ans;
        q.add(root);
        while(!q.isEmpty()){
            int size = q.size();
            int maxVal = Integer.MIN_VALUE;
            for(int i = 0;i < size;i++){
                TreeNode node = q.poll();
                if(node.val >= maxVal) maxVal = node.val;
                if(node.left != null) q.add(node.left);
                if(node.right != null) q.add(node.right);
            }
            ans.add(maxVal);
        }
        return ans;
    }
}
```