Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.
BFS
Time Complexity
O(N)Space ComplexityO(N)思路
简单的BFS,每层更新最大值放入res
代码
public ListlargestValues(TreeNode root) { List res = new ArrayList (); if(root == null) return res; Queue queue = new LinkedList (); queue.offer(root); while(!queue.isEmpty()){ int size = queue.size(); int max = Integer.MIN_VALUE; for(int i = 0; i < size; i++){ TreeNode cur = queue.poll(); max = Math.max(cur.val, max); if(cur.left != null){ queue.offer(cur.left); } if(cur.right != null){ queue.offer(cur.right); } } res.add(max); } return res;}