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