1

题目

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]

讲解

又是树的层次遍历题。相同的题我已经做了两个了:637. Average of Levels in Binary Tree429. N-ary Tree Level Order Traversal

Java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> result = new ArrayList<>();
    public List<Integer> largestValues(TreeNode root) {
        if(root==null){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int count = 1;
        while(!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int floorSize = 0;
            for(int i=0;i<count;i++){
                TreeNode now = queue.poll();
                list.add(now.val);
                if(now.left!=null){
                    queue.offer(now.left);
                    floorSize++;
                }
                if(now.right!=null){
                    queue.offer(now.right);
                    floorSize++;
                }
            }
            int max = list.get(0);
            for(Integer x:list){
                if(max<x){
                    max = x;
                }
            }
            count = floorSize;
            result.add(max);
        }
        return result;
    }
}

liuqinh2s
42 声望13 粉丝

认真写代码,搞创作