本文主要是介绍leetcode515: Find Largest Value in Each Tree Row,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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]广度优先搜索用队列,深度优先搜索用堆栈(还有,程序第三行在eclipse中会报错,leetcode上可以运行)
public List<Integer> largestValues(TreeNode root) {List<Integer> list = new ArrayList<Integer>();Queue<TreeNode> queue = new LinkedList<>();if(root != null)queue.offer(root);while(!queue.isEmpty()) {int max = queue.peek().val;int size = queue.size();for(int i = 0; i < size; i++) {TreeNode node = queue.poll();max = Math.max(max, node.val);if(node.right != null) queue.offer(node.right);if(node.left != null) queue.offer(node.left);}list.add(max);}return list;}
这篇关于leetcode515: Find Largest Value in Each Tree Row的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!