层序遍历的应用:
移步-LeetCode 515. 在每个树行中找最大值
移步->LeetCode 104. 二叉树的最大深度
移步->LeetCode 102. 二叉树的层序遍历
移步->LeetCode 226. 翻转二叉树
题目链接 515. 在每个树行中找最大值
思路:
采用层序遍历,每层计算得到最大值,然后每层遍历完后加入到结果列表中。注意,初始最大值设置为-(1 << 31)。
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> reslist = new ArrayList<Integer>();
if(root == null) return reslist;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(root);
while(!que.isEmpty()){
int len = que.size();
int max = -(1 << 31);
while(len>0){
TreeNode curNode = que.poll();
max = curNode.val>max?curNode.val:max;
if(curNode.left!=null) que.offer(curNode.left);
if(curNode.right!=null) que.offer(curNode.right);
len--;
}
reslist.add(max);
}
return reslist;
}
}