515. 在每个树行中找最大值
515. Find Largest Value in Each Tree Row
题目描述
You need to find the largest value in each row of a binary tree.
您需要在二叉树的每一行中找到最大的值。
LeetCode515. Find Largest Value in Each Tree Row
Example:
Input:
```
1
/ \
3 2
/ \ \
5 3 9
```
Output: [1, 3, 9]
```
1
/ \
3 2
/ \ \
5 3 9
```
Output: [1, 3, 9]
Java 实现
TreeNode Class
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
import java.util.LinkedList;
import java.util.List;
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new LinkedList<>();
helper(root, res, 0);
return res;
}
public void helper(TreeNode root, List<Integer> res, int depth) {
if (root == null) {
return;
}
if (depth == res.size()) {
res.add(root.val);
} else {
res.set(depth, Math.max(res.get(depth), root.val));
}
helper(root.left, res, depth + 1);
helper(root.right, res, depth + 1);
}
}
参考资料