leetcode--515. Find Largest Value in Each Tree Row

Posted Shihu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode--515. Find Largest Value in Each Tree Row相关的知识,希望对你有一定的参考价值。

1、问题描述

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]

 

2、边界条件:root==null

3、思路:层级遍历,每一层找到最大值,记录

4、代码实现

/**
 * 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> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int curLevelNum = 1;
        while (!queue.isEmpty()) {
            int nextLevelNum = 0;
            int max = Integer.MIN_VALUE;
            while (curLevelNum-- > 0) {
                TreeNode top = queue.poll();
                max = Math.max(max, top.val);
                if (top.left != null) {
                    queue.offer(top.left);
                    nextLevelNum++;
                }
                if (top.right != null) {
                    queue.offer(top.right);
                    nextLevelNum++;
                }
            }
            result.add(max);
            curLevelNum = nextLevelNum;
        }
        return result;
    }
}

 

5、api

以上是关于leetcode--515. Find Largest Value in Each Tree Row的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-515-Find Largest Value in Each Tree Row]

[LeetCode]515 Find Largest Value in Each Tree Row(dfs)

(BFS 二叉树) leetcode 515. Find Largest Value in Each Tree Row

leetcode515- Find Largest Value in Each Tree Row- medium

Python描述 LeetCode 515. 在每个树行中找最大值

Python描述 LeetCode 515. 在每个树行中找最大值