515. Find Largest Value in Each Tree Row

Link

Solution

BFS level traversal and pick max of each level

public List<Integer> largestValues(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        if(root == null) return ret;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        
        while(!queue.isEmpty()){
            int count = queue.size();
            int max = Integer.MIN_VALUE;
            for(int i = 0; i < count; i++){
                TreeNode node = queue.poll();
                max = Math.max(max, node.val);
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
            }
            ret.add(max);
        }
        return ret;
        
    }

Last updated

Was this helpful?