You are given the root
of a binary tree. Find the value of the leftmost node in the last row of the tree.
Return the leftmost value in the last row of the tree.
Input: root = [2,1,3]
Output: 1
[1, 10^4]
.-2^31 <= Node.val <= 2^31 - 1
We will use a Breadth-First Search (BFS) approach to solve this problem. BFS is well-suited for this task because it explores nodes level by level from left to right. This way, when we reach the last level of the tree, we can simply record the first node’s value encountered at that level.
Here’s the code to achieve the above strategy:
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findBottomLeftValue(root: TreeNode) -> int:
if not root:
return -1 # Edge case handling
queue = deque([root])
# To store the leftmost value of the last row
leftmost_value = root.val
while queue:
# Number of nodes at the current level
num_nodes_at_level = len(queue)
for i in range(num_nodes_at_level):
node = queue.popleft()
# For the first node in this level, set the leftmost_value
if i == 0:
leftmost_value = node.val
# Add child nodes of the current node into the queue
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return leftmost_value
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?