本文主要是介绍leetcode515 Find Largest Value In Each Tree Row Java,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、用队列进行处理。分别找到每一行中的最大值。
public List<Integer> largestValues(TreeNode root) {List<Integer> result = new ArrayList<>();if(root == null) {return result;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while(! queue.isEmpty()) {int size = queue.size();int max = Integer.MIN_VALUE;for(int i=0; i<size; i++){TreeNode curr = queue.poll();max = Math.max(max, curr.val);if(curr.left != null) queue.offer(curr.left);if(curr.right != null) queue.offer(curr.right);}result.add(max);}return result;}
2、递归解法
List<Integer> result = new ArrayList<>();public List<Integer> largestValues(TreeNode root) {
// if(root != null) result.add(root.val);helper(root,0);return result;}public void helper(TreeNode root, int dep) {if(root == null) return;if(dep == result.size()) {result.add(root.val);}else {result.set(dep, Math.max(root.val,result.get(dep)));}helper(root.left,dep+1);helper(root.right,dep+1);}
这篇关于leetcode515 Find Largest Value In Each Tree Row Java的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!