(LeetCode)515.Find Largest Value in Each Tree Row

1.Description(Medium)

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]

2.Code

维护一个变量去找到每次的最大值

public List<Integer> largestValues(TreeNode root) {
        List<Integer> result=new ArrayList<Integer>();
        if(root==null){
            return result;
        }
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size=queue.size();
            int max=Integer.MIN_VALUE;
            for(int i=0;i<size;i++){
                TreeNode current=queue.poll();
                max=Math.max(max,current.val);
                if(current.left!=null){
                    queue.offer(current.left);
                }
                if(current.right!=null){
                    queue.offer(current.right);
                }
            }
            result.add(max);
        }
        return result;
    }

Last updated