LeetCode 515. Find Largest Value in Each Tree Row

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 }

 

 
posted @ 2017-02-20 12:05  Black_Knight  阅读(580)  评论(0编辑  收藏  举报