[LeetCode] 515. Find Largest Value in Each Tree Row
Given the root
of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:
Input: root = [1,3,2,5,3,null,9] Output: [1,3,9]
Example 2:
Input: root = [1,2,3] Output: [1,3]
Example 3:
Input: root = [1] Output: [1]
Example 4:
Input: root = [1,null,2] Output: [1,2]
Example 5:
Input: root = [] Output: []
Constraints:
- The number of nodes in the tree will be in the range
[0, 104]
. -231 <= Node.val <= 231 - 1
在每个树行中找最大值。
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-largest-value-in-each-tree-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题其实很简单,BFS和DFS都能做,着重掌握DFS的方法。
BFS
就是普通的层序遍历,遍历的时候记录每一层上的最大值,放入结果集即可。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public List<Integer> largestValues(TreeNode root) { 3 List<Integer> res = new ArrayList<>(); 4 // corner case 5 if (root == null) { 6 return res; 7 } 8 // normal case 9 Queue<TreeNode> queue = new LinkedList<>(); 10 queue.offer(root); 11 while (!queue.isEmpty()) { 12 int size = queue.size(); 13 int max = Integer.MIN_VALUE; 14 for (int i = 0; i < size; i++) { 15 TreeNode cur = queue.poll(); 16 max = Math.max(max, cur.val); 17 if (cur.left != null) { 18 queue.offer(cur.left); 19 } 20 if (cur.right != null) { 21 queue.offer(cur.right); 22 } 23 } 24 res.add(max); 25 } 26 return res; 27 } 28 }
DFS
DFS的做法是在比较当前结果集的 size 和树的深度 level。如果当前 res.size + 1 == level,说明 DFS 已经在处理下一层了,此时先把下一层的 root 节点放到结果集。在遍历当前层的时候,如果 res.size == level,则需要把结果集中当前层的那个最大值拿出来跟当前遍历到的节点值作比较,并把较大的那一个再更新回结果集。这里有一个有配图的题解,帮助理解 DFS 是怎么运行的。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public List<Integer> largestValues(TreeNode root) { 3 List<Integer> res = new ArrayList<>(); 4 // corner case 5 if (root == null) { 6 return res; 7 } 8 helper(res, root, 1); 9 return res; 10 } 11 12 private void helper(List<Integer> res, TreeNode root, int depth) { 13 if (root == null) { 14 return; 15 } 16 if (depth == res.size() + 1) { 17 res.add(root.val); 18 } else { 19 res.set(depth - 1, Math.max(res.get(depth - 1), root.val)); 20 } 21 helper(res, root.left, depth + 1); 22 helper(res, root.right, depth + 1); 23 } 24 }