Sponsored
Sponsored
Using a BFS approach, we can efficiently explore each level of the tree from top to bottom. At each level, we keep track of the first value. The leftmost value in the last row will be the first value at the deepest level, which is the last processed level in BFS.
Time Complexity: O(n), where n is the number of nodes, as each node is visited once.
Space Complexity: O(n) in the worst case, for the queue storing nodes at the deepest level.
1import java.util.*;
2
3public class Solution {
4 public int findBottomLeftValue(TreeNode root) {
5 Queue<TreeNode> queue = new LinkedList<>();
6 queue.offer(root);
7 TreeNode node = null;
8 while (!queue.isEmpty()) {
9 node = queue.poll();
10 if (node.right != null) queue.offer(node.right);
11 if (node.left != null) queue.offer(node.left);
12 }
13 return node.val;
14 }
15}
This Java solution uses a LinkedList as a queue for BFS. Nodes are enqueued from right to left at each level. The last node processed this way is the deepest leftmost node.
For the DFS approach, we explore as deep as possible, preferring left subtrees over right. We track the maximum depth, updating the leftmost value encountered at each depth level. This ensures the leftmost node at the deepest level is found.
Time Complexity: O(n), as each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to recursive call stack.
1public class
This Java solution uses a helper DFS method, tracking the maximum depth, updating the leftmost value whenever a new deepest level is reached, and prioritizing left children.