Train of thought

Sequence traversal, find the maximum value on each level

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(! queue.isEmpty()) {int size = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.removeFirst();
                if(cur.left ! =null) {
                    queue.add(cur.left);
                }
                if(cur.right ! =null) {
                    queue.add(cur.right);
                }
                max = Math.max(cur.val, max);
            }
            res.add(max);
        }
        returnres; }}Copy the code