首页 > 其他 > 详细

LeetCode 515. Find Largest Value in Each Tree Row

时间:2017-02-20 13:38:38      阅读:307      评论:0      收藏:0      [点我收藏+]

515. Find Largest Value in Each Tree Row

Description Submission Solutions

  • Total Accepted: 3804
  • Total Submissions: 7252
  • Difficulty: Medium
  • Contributors: love_FDU_llp

You need to find the largest value in each row of a binary tree.

Example:

Input: 

          1
         /         3   2
       / \   \  
      5   3   9 

Output: [1, 3, 9] 

Subscribe to see which companies asked this question.

【题目分析】
给定一颗二叉树,返回二叉树中每一层的最大值。
【思路】
这是一个典型的二叉树层序遍历的问题,需要使用队列来解决。关于java队列的使用,计划详细了解一下。
【java代码】
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<Integer> largestValues(TreeNode root) {
12         List<Integer> res = new ArrayList<>();
13         Queue<TreeNode> queue = new LinkedList<>();
14         
15         if(root != null) queue.offer(root);
16         
17         while(!queue.isEmpty()) {
18             int max = Integer.MIN_VALUE;
19             int size = queue.size();
20             for(int i = 0; i < size; i++) {
21                 TreeNode node = queue.poll();
22                 max = Math.max(max, node.val);
23                 if(node.right != null) queue.offer(node.right);
24                 if(node.left != null) queue.offer(node.left);
25             }
26             res.add(max);
27         }
28         
29         return res;
30     }
31 }

 

 

LeetCode 515. Find Largest Value in Each Tree Row

原文:http://www.cnblogs.com/liujinhong/p/6418921.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!