Description
You need to find the largest value in each row of a binary tree.
Example:
Input:
Output: [1, 3, 9]
Solution
BFS, time O(n), space O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> largestValues = new ArrayList<>();
if (root == null) {
return largestValues;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;
while (size-- > 0) {
TreeNode curr = queue.poll();
max = Math.max(max, curr.val);
if (curr.left != null) queue.offer(curr.left);
if (curr.right != null) queue.offer(curr.right);
}
largestValues.add(max);
}
return largestValues;
}
}
DFS base on depth, time O(n), space O(h)
Just a simple pre-order traverse idea. Use depth to expand result list size and put the max value in the appropriate position.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> largestValues = new ArrayList<>();
helper(root, 0, largestValues);
return largestValues;
}
private void helper(TreeNode root, int depth, List<Integer> largestValues) {
if (root == null) {
return;
}
if (depth == largestValues.size()) {
largestValues.add(root.val);
}
largestValues.set(depth, Math.max(largestValues.get(depth), root.val));
helper(root.left, depth + 1, largestValues);
helper(root.right, depth + 1, largestValues);
}
}