1. 程式人生 > >leetcode--515. Find Largest Value in Each Tree Row

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

largest input http code poll() pro tps pub curl

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