space: O(D) to keep the queues, where D is a tree diameter. Let's use the last level to estimate the queue size. This level could contain up to N/2N/2 tree nodes in the case of complete binary tree.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */classSolution {publicList<Integer> largestValues(TreeNode root) {List<Integer> res =newArrayList<>();if (root ==null) return res;Queue<TreeNode> queue =newLinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size =queue.size();int max =Integer.MIN_VALUE;for (int i =0; i < size; i++) {TreeNode node =queue.poll(); max =Math.max(max,node.val);if (node.left!=null) queue.offer(node.left);if (node.right!=null) queue.offer(node.right); }res.add(max); }return res; }}