Medium
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
居然又等到一道不看答案做出来的题。这道题我就用的BFS的level order traversal, 取最后一层的第一个元素返回就好了。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++){
TreeNode curt = queue.poll();
level.add(curt.val);
if (curt.left != null){
queue.offer(curt.left);
}
if (curt.right != null){
queue.offer(curt.right);
}
}
res.add(level);
}
return res.get(res.size() - 1).get(0);
}
}
当然也可以稍微地简化一下,不用保存整个traversal的List,每次只需要记录每一层第一个元素(即最左边)的元素就可以了,用到了queue.peek()这个方法。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
int res = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
res = queue.peek().val;
for (int i = 0; i < size; i++){
TreeNode curt = queue.poll();
if (curt.left != null){
queue.offer(curt.left);
}
if (curt.right != null){
queue.offer(curt.right);
}
}
}
return res;
}
}