Skip to main content

Find Bottom Left Tree Value

LeetCode 513 | Difficulty: Medium​

Medium

Problem Description​

Given the root of a binary tree, return the leftmost value in the last row of the tree.

Example 1:

Input: root = [2,1,3]
Output: 1

Example 2:

Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7

Constraints:

- The number of nodes in the tree is in the range `[1, 10^4]`.

- `-2^31 <= Node.val <= 2^31 - 1`

Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree


Approach​

Tree DFS​

Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β†’ go right β†’ combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.

When to use

Path problems, subtree properties, tree structure manipulation.

Tree BFS (Level-Order)​

Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.

When to use

Level-order traversal, level-based aggregation, right/left side view.


Solutions​

Solution 1: C# (Best: 112 ms)​

MetricValue
Runtime112 ms
MemoryN/A
Date2018-07-15
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int FindBottomLeftValue(TreeNode root) {
Queue<TreeNode> level = new Queue<TreeNode>();
level.Enqueue(root);
TreeNode leftMost = null;
while(level.Count!=0)
{
var rowCount = level.Count();
leftMost = level.Peek();
for (int i = 0; i < rowCount; i++)
{
var dequeued = level.Dequeue();
if(dequeued.left!=null)
{
level.Enqueue(dequeued.left);
}
if (dequeued.right != null)
{
level.Enqueue(dequeued.right);
}
}

}
return leftMost.val;
}
}

Complexity Analysis​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Consider: "What information do I need from each subtree?" β€” this defines your recursive return value.