力扣 515 在每个树行找最大值(广度优先搜索)

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
   看出来是分层,我们就能知道是层序遍历,层序遍历就要用到广度优先搜索。

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

我们需要找到每一层的最大值,而queue.size()其实维护的就是每一层的数量,当走完一次size大小,这一层的max就可以定下来了。最后将max加入到list中就ok

总结

二叉树的层序遍历中。queue.size()维护的就是每一层的数量,所以牵扯到按层操作的,基本上都要用到这个。

猜你喜欢

转载自blog.csdn.net/weixin_51656756/article/details/121549486