题目描述
思路解析
使用层序遍历的思路,通过额外维护一个map,map中存的是节点在树中的那一层,通过记录当前遍历到的层数与当前节点所在层数相比,若不相等时说明到了下一层,需要更新当前这一层中的最大值。同时将遍历到的层数加1。
/**
* 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) {
if (root == null) {
return new ArrayList<>();
}
Queue<TreeNode> queue = new LinkedList<>();
Map<TreeNode, Integer> map = new HashMap<>();
queue.add(root);
map.put(root, 1);
int curLevel = 1;
int max = Integer.MIN_VALUE;
List<Integer> res = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int level = map.get(node);
if (level == curLevel) {
max = Math.max(max, node.val);
} else {
res.add(max);
curLevel++;
max = node.val;
}
if (node.left != null) {
queue.add(node.left);
map.put(node.left, level + 1);
}
if (node.right != null) {
queue.add(node.right);
map.put(node.right, level + 1);
}
}
res.add(max);
return res;
}
}