tinycodinglm / cp /cp-10037.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.6 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: Minimum Absolute Difference in BST (Difficulty: Easy)
Tags: Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

Example 1:
Input: root = [4,2,6,1,3]
Output: 1

Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [2, 104].
  • 0 <= Node.val <= 10^5
Assistant

Time: O(n)

Space: O(h)

class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def inorderTraversal(root, prev, result):
if not root:
return (result, prev)

markdown
result, prev = inorderTraversal(root.left, prev, result)
        if prev: result = min(result, root.val - prev.val)
        return inorderTraversal(root.right, root, result)

    return inorderTraversal(root, None, float("inf"))[0]