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.
给出一棵二叉树,输出最左边的叶子节点的值,假设root不是NULL
思路:
因为要输出最后一层最左边的叶子节点的值,考虑BFS按层输出,
最左边的叶子节点在最后,所以每层按从右到左的顺序加入list
最后一个值就是最左边的叶子节点的值
public int findBottomLeftValue(TreeNode root) {
int result = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode tmp = queue.poll();
result = tmp.val;
if(tmp.right != null) {
queue.offer(tmp.right);
}
if(tmp.left != null) {
queue.offer(tmp.left);
}
}
return result;
}