Problem
Given theroot of a binary tree, return the leftmost value in the last row of the tree.
Examples
Constraints
- The number of nodes in the tree is in the range
[1, 10^4]. -2^31 <= Node.val <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 513 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 513 # by problem number
lcpy gen -s find_bottom_left_tree_value # by problem name
root of a binary tree, return the leftmost value in the last row of the tree.
Input: root = [2,1,3]
Output: 1
Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7
[1, 10^4].-2^31 <= Node.val <= 2^31 - 1from collections import deque
from leetcode_py import TreeNode
class Solution:
# Time: O(n)
# Space: O(n)
def find_bottom_left_value(self, root: TreeNode[int]) -> int:
queue: deque[TreeNode[int]] = deque([root])
leftmost = root.val
while queue:
leftmost = queue[0].val
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return leftmost
| Time | Space |
|---|---|
| O(n) | O(n) |