515. Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.
Example:
Example:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
思路:题目意思为找到二叉树在每一层的最大值。递归把每个节点的值按层数区分传入List中
代码如下:
public class FindLargestValueinEachTreeRow { public List<Integer> largestValues(TreeNode root) { List<Integer> res = new ArrayList<>(); dfs(root, res, 0); return res; } public static void dfs(TreeNode node, List<Integer> res, int deepth) { if (node == null) return; if (deepth == res.size()) { res.add(node.val); } else { res.set(deepth, Math.max(res.get(deepth), node.val)); } dfs(node.left, res, deepth + 1); dfs(node.right, res, deepth + 1); } }