leetcode515- Find Largest Value in Each Tree Row- medium
Posted jasminemzy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode515- Find Largest Value in Each Tree Row- medium相关的知识,希望对你有一定的参考价值。
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]
算法:
1.BFS。层级遍历,每层打擂台。
2.DFS。记录从上到下的深度,每层参数里传下去+1即可。(从下到上的深度是通过回传int返回值来递归实现的)。每次根据当前深度d跟List<Integer>里对应位置的值打擂台。注意List的set用法。list.set(d, Math.max(list.get(d), n.val));
实现:
1.BFS
/** * 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> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { int size = q.size(); int max = Integer.MIN_VALUE; for (int i = 0; i < size; i++) { TreeNode n = q.poll(); max = Math.max(max, n.val); if (n.left != null) { q.offer(n.left); } if (n.right != null) { q.offer(n.right); } } result.add(max); } return result; } }
2.DFS
public class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); helper(root, res, 0); return res; } private void helper(TreeNode root, List<Integer> res, int d){ if(root == null){ return; } //expand list size if(d == res.size()){ res.add(root.val); } else{ //or set value res.set(d, Math.max(res.get(d), root.val)); } helper(root.left, res, d+1); helper(root.right, res, d+1); } }
以上是关于leetcode515- Find Largest Value in Each Tree Row- medium的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]515 Find Largest Value in Each Tree Row(dfs)
[leetcode-515-Find Largest Value in Each Tree Row]
(BFS 二叉树) leetcode 515. Find Largest Value in Each Tree Row
leetcode515- Find Largest Value in Each Tree Row- medium