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;
    }

 

posted @ 2019-07-17 19:14  月半榨菜  阅读(102)  评论(0编辑  收藏  举报