原题
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,从右向左搜索
解法(同最优解)
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
TreeNode last = root;
queue.offer(root);
while (!queue.isEmpty()) {
last = queue.poll();
if (last.right != null) {
queue.offer(last.right);
}
if (last.left != null) {
queue.offer(last.left);
}
}
return last.val;
}