Skip to content
Problem 513 · LeetCode 513(opens in a new tab)

Find Bottom Left Tree Value

MediumBreadth-first search

A binary tree with at least one node is handed to you through its root.

Look at the deepest row of the tree, the nodes farthest from the root. Return the value of the node that sits furthest to the left in that row. It does not have to be a left child: it is simply the first node of the bottom row when the row is read left to right.

Example 1

Input:  root = [4, 6, 1, null, null, 8, 3]
Output: 8
Why:    the bottom row is [8, 3]
2 more examples and the constraints

Example 2

Input:  root = [7]
Output: 7
Why:    the root is the only row

Example 3

Input:  root = [2, 5, 9, 4, null, null, 1, null, null, 6]
Output: 6
Why:    6 is alone in the bottom row

Constraints

  • The tree has between 1 and 10,000 nodes
  • Each node value is a 32-bit signed integer, from −2,147,483,648 to 2,147,483,647

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DFS, deepest first arrivalO(n)
  2. BFS, right to leftO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
DFS, deepest first arrivalO(n)
Passes; deep trees need a big stack
BFS, right to leftO(n)
Best; the last pop is the answer

n = number of nodes, h = tree height, w = widest row. Both touch every node once.

Edge cases to test

  • One node. [7] has a single row, so the answer is the root, 7.
  • Bottom node on the right side. In Example 3 the only bottom node, 6, hangs under the root's right subtree. Following left children alone would give the wrong answer, 4.
  • Right chain. [1, null, 2, null, 3] gives 3: a single node per row.
  • Negative values. The answer can be −2,147,483,648, so do not use a sentinel value for "no answer yet".

Common mistakes

  • Following left children down from the root, which misses a deeper row on the right.
  • Pushing left before right in the BFS, which returns the bottom row's rightmost node.
  • In the DFS, updating on depth >= best instead of depth > best, so a later node on the right overwrites the leftmost one.

How to talk through it

  1. 1Clarify. Is the tree ever empty? Does "leftmost" mean a left child, or the first node of the bottom row?
  2. 2Name the traversal. The answer is about rows, so a level-order traversal (BFS) fits.
  3. 3Flip the push order. Push right before left so each row comes out right to left; the last pop is the answer.
  4. 4Mention the DFS. Left-first DFS that updates only on a strictly deeper node gives the same answer with O(h) space.
  5. 5Test out loud. Run a single node, a right chain and a tree whose bottom node is on the right.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?