首页 > 代码库 > 515. Find Largest Value in Each Tree Row
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]
经典bfs, 不多说
/** * 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> ans = new ArrayList<>(); if (root == null) return ans; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { int size = q.size(); int max = Integer.MIN_VALUE; while (size > 0) { TreeNode cur = q.poll(); size--; max = Math.max(cur.val, max); if (cur.left != null) { q.offer(cur.left); } if (cur.right != null) { q.offer(cur.right); } } ans.add(max); } return ans; } }
515. Find Largest Value in Each Tree Row
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。