Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LC 515. 在每个树行中找最大值 #29

Open
HealUP opened this issue May 18, 2023 · 0 comments
Open

LC 515. 在每个树行中找最大值 #29

HealUP opened this issue May 18, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 18, 2023

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

思路:层序遍历,取每一层的最大值,放到一维数组,最后返回结果集

Collections.emptyList()//这个方法返回的List是Collections类的一个静态内部类,它继承AbstractList后并没有实现add()、remove()等方法,因此这个返回值List并不能增加删除元素
  • 层序遍历
  • 处理每一层的时候找到最大值即可

用到:

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();//直接返回空列表,减少开销
        }
        Queue<TreeNode> que = new LinkedList<>();//创建队列
        List<Integer> res = new ArrayList<>();//结果集
        que.offer(root);//根节点入队
        while (!que.isEmpty()) {
            int len = que.size();//记录当前节点的数量
            int max = Integer.MIN_VALUE;//先赋予int类型的最小值
            for (int i = 0; i < len; i++) {//找每一层的最大值
                TreeNode node = que.poll();//从队列中取出元素
                max = Math.max(max, node.val);//找出该层的最大值
                //放入该节点的左右节点到队列
                if (node.left != null) que.offer(node.left);
                if (node.right != null) que.offer(node.right);
            }
            //将每一层的最大值放到结果集
            res.add(max);
        }
        return res;
    }
}
@HealUP HealUP added 算法 记录刷题记录,代码随想录 二叉树 labels May 18, 2023
@HealUP HealUP removed the 二叉树 label Jul 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录刷题记录,代码随想录
Projects
None yet
Development

No branches or pull requests

1 participant