原题链接
思路
- BFS
- 队列中只会保存一层的节点,每次会将上一层的点全部出队,并将这一层的点全部入队,这样队头元素就是每一层最左边的点。
- 时间复杂度:O(n)
代码
class Solution {
public int findBottomLeftValue(TreeNode root) {
LinkedList<TreeNode> list = new LinkedList<>();
if(root == null) return -1;
list.add(root);
int res = root.val;
int floor = 1;
while(!list.isEmpty()) {
for(int i = 0;i < floor; i++) {
TreeNode node = list.getFirst();
list.removeFirst();
if(i == 0) res = node.val;
if(node.left != null) list.add(node.left);
if(node.right != null) list.add(node.right);
}
floor = list.size();
}
return res;
}
}