题目:
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]分析:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
//给定二叉树,找出每层最大的数据
//思路:层序遍历整个树,然后从每层中找出最大的数
List<Integer> list=new ArrayList<>();
if(root==null) return list;
Queue<TreeNode> oddQu=new LinkedList<>();
Queue<TreeNode> evenQu=new LinkedList<>();
oddQu.add(root);
int count=1;
while(!oddQu.isEmpty()||!evenQu.isEmpty()){
int cur=Integer.MIN_VALUE;
while(count%2==1&&!oddQu.isEmpty()){
TreeNode temp=oddQu.poll();
cur=Math.max(temp.val,cur);
if(temp.left!=null){
evenQu.add(temp.left);
}
if(temp.right!=null){
evenQu.add(temp.right);
}
}
//偶数层
while(count%2==0&&!evenQu.isEmpty()){
TreeNode temp=evenQu.poll();
cur=Math.max(temp.val,cur);
if(temp.left!=null){
oddQu.add(temp.left);
}
if(temp.right!=null){
oddQu.add(temp.right);
}
}
count++;
list.add(cur);
}
return list;
}
}