algoadvance

Given a Binary Search Tree (BST), you need to find the minimum absolute difference between values of any two nodes in the BST.

Clarifying Questions:

  1. Input Type:
    • Can the BST contain duplicate values? (Typically, a BST should not contain duplicate values.)
    • How large can the tree be? (This helps to consider time and space complexity constraints.)
  2. Output Type:
    • Should we return the minimum absolute difference as an integer?

Strategy:

To find the minimum absolute difference in a BST:

  1. Inorder Traversal: Utilize the properties of BST where an inorder traversal yields nodes in sorted order. This helps in evaluating the difference between subsequent elements easily.
  2. Calculate Min Difference: As we traverse, keep track of the previous node value and compute the difference with the current node value. Track the minimum of these differences.

Code:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def getMinimumDifference(root: TreeNode) -> int:
    def inorder_traversal(node):
        nonlocal prev, min_diff
        if not node:
            return
        inorder_traversal(node.left)
        if prev is not None:
            min_diff = min(min_diff, node.val - prev)
        prev = node.val
        inorder_traversal(node.right)
    
    prev = None
    min_diff = float('inf')
    inorder_traversal(root)
    return min_diff

Strategy Explanation:

  1. Inorder Traversal:
    • Traverse the left subtree.
    • Process the current node.
    • Traverse the right subtree.
    • This ensures that the nodes are processed in ascending order of their values, due to the properties of the BST.
  2. Tracking Minimum Difference:
    • Maintain a prev variable to store the value of the previously visited node.
    • Compute the difference between the current node’s value and prev.
    • Update min_diff if the computed difference is smaller than the current min_diff.
  3. Initialization:
    • Start with prev as None.
    • Set min_diff to a large value (float('inf')), to ensure any actual difference found will be smaller.
  4. Recursive Function:
    • The inorder_traversal function is called recursively, ensuring the entire tree is traversed and compared.

Time Complexity:

This approach ensures an efficient and straightforward way to compute the minimum absolute difference in a BST.

Try our interview co-pilot at AlgoAdvance.com