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]
class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> res = new ArrayList(); List<List<Integer>> help = levelOrder(root); for(List<Integer> list : help) res.add(Collections.max(list)); return res; } public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Helper(0, root, res); return res; } public void Helper(int height, TreeNode p, List<List<Integer>> res){ if(p == null) return; if(height == res.size()){ res.add(new ArrayList()); } res.get(height).add(p.val); Helper(height + 1, p.left, res); Helper(height + 1, p.right, res); } }
先level order,再把每层最大的拉出来。
public class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); helper(root, res, 0); return res; } private void helper(TreeNode root, List<Integer> res, int d){ if(root == null){ return; } //expand list size if(d == res.size()){ res.add(root.val); } else{ //or set value res.set(d, Math.max(res.get(d), root.val)); } helper(root.left, res, d+1); helper(root.right, res, d+1); } }
或者直接用d记录层数,每遍历到一个就更新一次。
class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> res = new ArrayList(); if(root == null) return res; Queue<TreeNode> q = new LinkedList(); q.offer(root); while(!q.isEmpty()) { int size = q.size(); int cur = Integer.MIN_VALUE; for(int i = 0; i < size; i++) { TreeNode tmp = q.poll(); if(tmp.left != null) q.offer(tmp.left); if(tmp.right != null) q.offer(tmp.right); cur = Math.max(cur, tmp.val); } res.add(cur); } return res; } }
BFS,行!