https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/
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]
给定一个二叉树,将每一层中值最大的节点放在list
集合中返回
使用Queue队列进行层次遍历,每次遍历都记录一下当层最大的值即可
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
TreeNode max = new TreeNode(Integer.MIN_VALUE);
for(int i = 0; i < size; i++) {
TreeNode tn = queue.poll();
if(max.val < tn.val)
max = tn;
if(tn.left != null)
queue.add(tn.left);
if(tn.right != null)
queue.add(tn.right);
}
list.add(max.val);
}
return list;
}
}