您的位置:首页 > 产品设计 > UI/UE

LeetCode.515 Find Largest Value in Each Tree Row

2018-01-21 22:10 351 查看
题目:

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: