Solving Leetcode Interviews in Seconds with AI: Minimum Absolute Difference in BST
Introduction
In this blog post, we will explore how to solve the LeetCode problem "530" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. 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 <= 105 Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
Explanation
Here's the breakdown of the solution:
- Inorder Traversal: Perform an inorder traversal of the BST. Inorder traversal visits nodes in ascending order, which is crucial for efficiently finding the minimum difference between adjacent nodes.
- Track Previous Node: Maintain a variable to store the value of the previously visited node during the traversal.
Calculate and Update Minimum Difference: During the traversal, calculate the absolute difference between the current node's value and the previous node's value. Update the minimum difference found so far.
Time Complexity: O(N), where N is the number of nodes in the BST.
- Space Complexity: O(H), where H is the height of the BST (due to the recursion stack). In the worst-case scenario (skewed tree), H = N, resulting in O(N) space complexity. In the best and average cases (balanced tree), H = log N, resulting in O(log N) space complexity.
Code
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
self.min_diff = float('inf')
self.prev = None
def inorder(node):
if not node:
return
inorder(node.left)
if self.prev is not None:
self.min_diff = min(self.min_diff, abs(node.val - self.prev))
self.prev = node.val
inorder(node.right)
inorder(root)
return self.min_diff