LeetCode-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]
    public List<Integer> largestValues(TreeNode root) {
        List<Integer>re =new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        if(null==root){
            return re;
        }
        queue.offer(root);
        TreeNode cur = root;
        while(!queue.isEmpty()){
            int len = queue.size();
            int max = Integer.MIN_VALUE;
            for(int i=0;i<len;i++){
                cur = queue.poll();
                max = max>cur.val?max:cur.val;
                if(cur.left!=null) queue.offer(cur.left);
                if(cur.right!=null) queue.offer(cur.right);
            }
            re.add(max);
        }
        return re;
    }

猜你喜欢

转载自www.cnblogs.com/zhacai/p/11203098.html