515. 在每个树行中找最大值
这道题的本质还是层次遍历。且要把每层的给记录下来,
这题和102题很相似。
在进入循环的时候记录list的数目,就可以知道对应的层的数量。很关键啊
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null) return list;
LinkedList<TreeNode> link = new LinkedList<TreeNode>();
link.add(root);
while (!link.isEmpty()) {
int num = link.size();
int max = Integer.MIN_VALUE;
for(int i=0; i<num; i++) {
TreeNode node = link.poll();
max = Math.max(max, node.val);
if (node.left != null) {
link.add(node.left);
}
if (node.right != null) {
link.add(node.right);
}
}
list.add(max);
}
return list;
}
}
网友评论