Minimum Distance Between BST Nodes (Leetcode 783)

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

class Solution:
    def minDiffInBST(self, root: Optional[TreeNode]) -> int:
        
        global ans
        ans=float('inf')
        global prev
        prev=float('-inf')
        
        def fun(root):
            global ans
            global prev
            if(root is None):
                return
            fun(root.left)
            ans=min(ans,root.val-prev)
            prev=root.val
            fun(root.right)
        
        fun(root)
        return ans

Last updated