leetcode 515 在每个树行中找最大值

2022/2/4 23:13:02

本文主要是介绍leetcode 515 在每个树行中找最大值,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

思路

原题链接

  1. 每一层维护一个变量,用于存储最大值
  2. 注意:q.poll() 语句要在for循环内部执行
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        if (root == null) {
            return result;
        }

        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        // 层序遍历
        while (!q.isEmpty()) {
            int sz = q.size();
            // 在每一层维护一个变量,用于存储最大值
            int max = Integer.MIN_VALUE;
            // 对每一层的元素进行遍历
            for (int i = 0; i < sz; i++) {
                TreeNode cur = q.poll();
                // 每取出来一个元素就进行一次比较
                max = Math.max(max, cur.val);

                // 添加下一层的元素
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
            // 将每一层的最大值添加到结果变量中
            result.add(max);
        }
        return result;
    }
}


这篇关于leetcode 515 在每个树行中找最大值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程