您的位置:首页 > 产品设计 > UI/UE

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:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: