515. Find Largest Value in Each Tree Row

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]

这题是BFS典型套路了,调试了几次过了。注意rowMax = Integer.MIN_VALUE;不要漏了。

public class Solution {
    public List largestValues(TreeNode root) {
        List result = new ArrayList<>();
        if (root == null) return result;
        
        LinkedList queue = new LinkedList<>();
        queue.offer(root);
        int curNum = 1;
        int nextNum = 0;
        int rowMax = Integer.MIN_VALUE;
        while (!queue.isEmpty()) {
            TreeNode temp = queue.poll();
            curNum--;
            if (temp.val > rowMax) rowMax = temp.val;

            if (temp.left != null) {
                queue.offer(temp.left);
                nextNum++;
            }

            if (temp.right != null) {
                queue.offer(temp.right);
                nextNum++;
            }

            if (curNum == 0) {
                result.add(rowMax);
                curNum = nextNum;
                nextNum = 0;
                rowMax = Integer.MIN_VALUE;
            }
        }
        return result ; 
    }
}

你可能感兴趣的:(515. Find Largest Value in Each Tree Row)