0515. Find Largest Value in Each Tree Row

515. Find Largest Value in Each Tree Row #

题目 #

给定一棵二叉树的根节点 root,找出该二叉树中每一层的最大值。

思路 #

代码 #

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;
    }
}
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ans = new LinkedList<>();
        if (root == null) return ans;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.size() != 0) {
            int layerSize = queue.size(), layerMax = queue.peek().val;
            
            for (int i = 0; i < layerSize; i++) {
                TreeNode node = queue.poll();
                
                layerMax = Math.max(layerMax, node.val);
                
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            
            ans.add(layerMax);
        }
        
        return ans;
    }
}