1、宽度优先遍历
public List largestValues(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List res = new ArrayList<>();
Queue queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int len = queue.size();
int maxVal = Integer.MIN_VALUE;
while (len > 0) {
len--;
TreeNode t = queue.poll();
maxVal = Math.max(maxVal, t.val);
if (t.left != null) {
queue.offer(t.left);
}
if (t.right != null) {
queue.offer(t.right);
}
}
res.add(maxVal);
}
return res;
} 2、递归
public List largestValues(TreeNode root) {
List list = new ArrayList<>();
dfs(root,0,list);
return list;
}
private void dfs(TreeNode root, int height,List list) {
if (root == null){
return;
}
if (list.size() <= height){
list.add(height,root.val);
}else {
list.set(height,Math.max(list.get(height),root.val));
}
height++;
dfs(root.left,height,list);
dfs(root.right,height,list);
} | 留言与评论(共有 0 条评论) “” |