Understanding the problem. WE can’t just go left and elft and find the answer. We can also have the answer in right part of the root. So, idea is to get the leftmost value in the last row. That implies doing level order traversal.
We will use Breadth-First Search (BFS) using a queue to traverse the tree level by level and ensure we capture the leftmost value at the last row. Here’s the approach:
Initialisation: Start the BFS traversal with the root node in the queue.
Update Row: At each level, iterate through all nodes in the current level of the queue. Keep track of the leftmost node at that level.
Leftmost Tracking: For each level, ensure the value stored corresponds to the first node in the level.
Continue Traversal: Add the left and right children of each node into the queue to enable processing of the next level.
Result: The last updated leftmost value is the answer.
classSolution {
publicintfindBottomLeftValue(TreeNode root) {
int ans = 0; // Result variable for the leftmost value Queue<TreeNode> queue =new LinkedList<>(); // BFS queue queue.add(root); // Start BFS from rootwhile (!queue.isEmpty()) {
int size = queue.size(); // Number of nodes at the current level ans = queue.peek().val; // Leftmost value in the current levelfor (int i = 0; i < size; i++) {
TreeNode curr = queue.poll(); // Remove current node from the queue// Add children to the queue for the next levelif (curr.left!=null) queue.add(curr.left);
if (curr.right!=null) queue.add(curr.right);
}
}
return ans; // The leftmost value at the last row }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
deffindBottomLeftValue(self, root: Optional[TreeNode]) -> int:
ans: int =0# Result variable queue: deque[TreeNode] = deque([root]) # BFS queue starting with rootwhile queue:
size: int = len(queue) # Number of nodes at current level ans = queue[0].val # Leftmost value in the current levelfor _ in range(size):
curr: Optional[TreeNode] = queue.popleft() # Remove current node from the queue# Add children to the queue for next levelif curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
return ans # The leftmost value at the last row
By traversing nodes right to left, we ensure that the last node processed at the deepest level during BFS is the leftmost node. Therefore, there’s no need to track the first element added; the last value in the traversal is the result.