#513

Find Bottom Left Tree Value

Medium
TreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchBreadth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal solution uses a depth-first search (DFS) approach to traverse the tree. By tracking the depth of each node, we can directly identify the leftmost value at the deepest level without needing to store all nodes.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to store the leftmost value and a variable to track the maximum depth.
  2. 2Step 2: Use a recursive DFS function that takes the current node and its depth as parameters.
  3. 3Step 3: If the current depth is greater than the maximum depth, update the leftmost value and maximum depth.
  4. 4Step 4: Traverse the left subtree first, then the right subtree.
solution.py17 lines
1# Full working Python code
2
3def findBottomLeftValue(root):
4    def dfs(node, depth):
5        nonlocal leftmost_value, max_depth
6        if not node:
7            return
8        if depth > max_depth:
9            max_depth = depth
10            leftmost_value = node.val
11        dfs(node.left, depth + 1)
12        dfs(node.right, depth + 1)
13
14    leftmost_value = root.val
15    max_depth = 0
16    dfs(root, 1)
17    return leftmost_value

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Using depth-first search allows us to efficiently find the leftmost value without storing all nodes.
  • 2The order of traversal matters; always explore the left child before the right child to ensure we find the leftmost node.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.