Problem statement

https://leetcode.com/problems/minimum-distance-between-bst-nodes/

Solution

The basic idea is to perform Inorder Traversal of BST, which will return values in increasing order. We can do it in recursive way.

Complexity

Time complexity will be O(n), space complexity is O(h).

Code

class Solution:
    def minDiffInBST(self, root):
        def dfs(node):
            if node.left: dfs(node.left)
            self.res = min(self.res, node.val - self.pre)
            self.pre = node.val
            if node.right: dfs(node.right)
        
        self.pre, self.res = -float('inf'), float("inf")
        dfs(root)
        return self.res