Leetcode——515. Find Largest Value in Each Tree Row(Queue解法)

题目原址

https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/

题目描述

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]

解题思路

给定一个二叉树,将每一层中值最大的节点放在list集合中返回

使用Queue队列进行层次遍历,每次遍历都记录一下当层最大的值即可

AC代码

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if(root == null) return list;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            TreeNode max = new TreeNode(Integer.MIN_VALUE);
            for(int i = 0; i < size; i++) {
                TreeNode tn = queue.poll();
                if(max.val < tn.val)
                    max = tn;
                if(tn.left != null)
                    queue.add(tn.left);
                if(tn.right != null)
                    queue.add(tn.right);
            }
            list.add(max.val);
        }
        return list;       
    }
}

你可能感兴趣的:(515.,Find,Largest,Value,in,Eac,Leetcode)