Skip to main content

🟡 剑指 Offer II 044. 二叉树每层的最大值

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

/** * 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; *     } * } */class Solution {    public List<Integer> largestValues(TreeNode root) {        List<Integer> res = new ArrayList<>();        int rowMin, rowSize;
        if (root == null) {            return res;        }        Deque<TreeNode> queue = new LinkedList<>();        queue.add(root);
        while (!queue.isEmpty()) {            rowMin = Integer.MIN_VALUE;            rowSize = queue.size();
            for (int i=0; i<rowSize; i+=1) {                TreeNode cur = queue.poll();                rowMin = Math.max(rowMin, cur.val);
                if (cur.left != null) {                    queue.add(cur.left);                }                if (cur.right != null) {                    queue.add(cur.right);                }            }
            res.add(rowMin);        }                return res;    }}