515. Find Largest Value in Each Tree Row

来源:互联网 发布:默纳克解密软件 编辑:程序博客网 时间:2024/06/04 17:56

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]

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> largestValues(TreeNode root) {        List<Integer> result = new ArrayList<Integer>();        if(root == null){            return result;        }        Queue<TreeNode> q = new LinkedList<TreeNode>();        q.offer(root);        while(!q.isEmpty()){            int size = q.size();            int max = Integer.MIN_VALUE;            for(int i=0; i<size; i++){                TreeNode cur = q.poll();                max = Math.max(cur.val, max);                if(cur.left != null){                    q.offer(cur.left);                }                if(cur.right != null){                    q.offer(cur.right);                }            }            result.add(max);        }        return result;    }}



原创粉丝点击