You need to find the largest value in each row of a binary tree.
Input:
1
/ \
3 2
/ \ \
5 3 9
Output:
[1, 3, 9]
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int curMax = Integer.MIN_VALUE, size = 0;
while (!queue.isEmpty()) {
size = queue.size();
curMax = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode curNode = queue.remove();
curMax = Math.max(curMax, curNode.val);
if (curNode.left != null) {
queue.add(curNode.left);
}
if (curNode.right != null) {
queue.add(curNode.right);
}
}
res.add(curMax);
}
return res;
}
}
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
getLargestValues(root, 0, res);
return res;
}
public void getLargestValues(TreeNode node, int depth, List<Integer> res) {
if (node == null) {
return;
}
if (res.size() <= depth) {
res.add(node.val);
}
else if (res.get(depth) < node.val) {
res.set(depth, node.val);
}
getLargestValues(node.left, depth + 1, res);
getLargestValues(node.right, depth + 1, res);
}
}
3. Time & Space Complexity