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.
1from collections import deque
2
3def findBottomLeftValue(root):
4 queue = deque([root])
5 while queue:
6 node = queue.popleft()
7 if node.right:
8 queue.append(node.right)
9 if node.left:
10 queue.append(node.left)
11 return node.val
This Python solution uses a queue to perform a BFS. Starting from the root, it processes each level while storing nodes in the queue from right to left. The last processed node's value will be the leftmost node at the deepest level.
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.
1def findBottomLeftValue(
This Python DFS solution recursively traverses the tree, increasing depth at each level. Whenever a greater depth is reached, it updates the leftmost value. Left children are processed before right.