tinycodinglm / cp /cp-10020.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.16 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Find Bottom Left Tree Value (Difficulty: Medium)
Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree

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, 104].
  • -2^31 <= Node.val <= 2^31 - 1
Assistant

Time: O(n)

Space: O(h)

class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def findBottomLeftValueHelper(root, curr_depth, max_depth, bottom_left_value):
if not root:
return max_depth, bottom_left_value
if not root.left and not root.right and curr_depth+1 > max_depth:
return curr_depth+1, root.val
max_depth, bottom_left_value = findBottomLeftValueHelper(root.left, curr_depth+1, max_depth, bottom_left_value)
max_depth, bottom_left_value = findBottomLeftValueHelper(root.right, curr_depth+1, max_depth, bottom_left_value)
return max_depth, bottom_left_value

markdown
result, max_depth = 0, 0
    return findBottomLeftValueHelper(root, 0, max_depth, result)[1]

Time: O(n)

Space: O()

import collections

class Solution2(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
last_node, q = None, collections.deque([root])
while q:
last_node = q.popleft()
q.extend([n for n in [last_node.right, last_node.left] if n])
return last_node.val