leetcode515_在每个树行中找最大值

您需要在二叉树的每一行中找到最大的值。

示例:

输入: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

输出: [1, 3, 9]

 

 

思路:

层序遍历的思想  在同一层找最大的

    public List<Integer> largestValues(TreeNode root) {
	  List<Integer> res = new ArrayList<Integer>();    
	  if (root==null) return res;  
	    Queue<TreeNode> queue = new LinkedList<TreeNode>();
	    queue.add(root);
	       
	    while(queue.size() != 0){
	       int size = queue.size();       //每层的数目量
	       int max = Integer.MIN_VALUE;   //用于保存每层的最大值
	       for(int i = 0; i < size; i++){
	            TreeNode cur = queue.poll();
	            max=Math.max(cur.val, max);
	            if(cur.left!= null)queue.add(cur.left);
	            if(cur.right!=null)queue.add(cur.right);
	          }
	       res.add(max);
	     }	
	 return res;
	}

 

全部评论

相关推荐

07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
想按时下班的大菠萝在...:隔壁学校的,加油多投, 实在不好找可以下个学期开学找,把算法八股准备好,项目有空再换换
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务