LeetCode 513: Find Bottom Left Tree Value
Problem Description
Explanation
To find the bottom left value in a binary tree, we can perform a level-order traversal (BFS) starting from the root. At each level, we iterate through all nodes in that level from left to right. The last node visited in the last level will be the bottom left value.
- Time complexity: O(N) where N is the number of nodes in the tree
- Space complexity: O(N) for the queue used in BFS
Solutions
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int leftmost = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == 0) {
leftmost = node.val;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return leftmost;
}
}
Related LeetCode Problems
Loading editor...