515. Find Largest Value in Each Tree Row

来源:互联网 发布:美容保健品 知乎 编辑:程序博客网 时间:2024/06/17 20:49

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]

Subscribe to see which companies asked this question.

/** * 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> re = new ArrayList<Integer>();if (root == null)return re;LinkedList<TreeNode> data = new LinkedList<TreeNode>();data.add(root);while (!data.isEmpty()) {int max = Integer.MIN_VALUE;int i = data.size();while (i > 0) {TreeNode temp = data.pop();max = Math.max(max, temp.val);if (temp.left != null)data.add(temp.left);if (temp.right != null)data.add(temp.right);i--;}re.add(max);}return re;    }}


0 0