leetcode515: Find Largest Value in Each Tree Row
2017-02-23 20:51
363 查看
You need to find the largest value in each row of a binary tree.
Example:
广度优先搜索用队列,深度优先搜索用堆栈(还有,程序第三行在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;
}
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;
}
相关文章推荐
- Find Largest Value in Each Tree Row
- LeetCode.515 Find Largest Value in Each Tree Row
- 第十二周算法分析与设计: Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- LeetCode: Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row问题及解法
- Week Training: 515 Find Largest Value in Each Tree Row
- LeetCode 515 Find Largest Value in Each Tree Row(二叉树层序遍历)
- [leetcode 515]Find Largest Value in Each Tree Row
- LeetCode之Find Largest Value in Each Tree Row(Kotlin)
- Leetcode 515 Find Largest Value in Each Tree Row
- LeetCode:Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- LeetCode#515 Find Largest Value in Each Tree Row (week15)
- Find Largest Value in Each Tree Row
- Medium:Find Largest Value in Each Tree Row
- LeetCode#515 Find Largest Value in Each Tree Row
- 【LEETCODE】 Find Largest Value in Each Tree Row javascript实现
- 算法分析与设计丨第三周丨LeetCode(6)——Find Largest Value in Each Tree Row(Medium)
- LeetCode——Find Largest Value in Each Tree Row