题目
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例
输入: root = [2,1,3]
输出: 1
输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/LwUNpT
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:BFS
Java实现
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int ans = 0;
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
if (i == 0) ans = cur.val;
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
}
return ans;
}
}