# BFS and DFS Java solution

• BFS

``````public class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;
while (size > 0) {
TreeNode cur = queue.pollFirst();
max = Math.max(max, cur.val);
if (cur.left != null) {
}
if (cur.right != null) {
}
size--;
}
}
return result;
}
}
``````

DFS

``````public class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
largestValues(root, 0, result);
return result;
}
private void largestValues(TreeNode root, int level, List<Integer> result) {
if (level >= result.size()) {
} else if (root.val > result.get(level)) {
result.set(level, root.val);
}
if (root.left != null) {
largestValues(root.left, level + 1, result);
}
if (root.right != null) {
largestValues(root.right, level + 1, result);
}
}
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.