Skip to content

Latest commit

 

History

History
42 lines (31 loc) · 832 Bytes

783.md

File metadata and controls

42 lines (31 loc) · 832 Bytes

Minimum Distance Between BST Nodes

Description

link


Solution

  • See Code

Code

Complexity T : O(N) M : O(n)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDiffInBST(self, root: TreeNode) -> int:
        stack = []
        ans, pre = float("inf"), float("-inf")
        while root or stack:
            if root:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                ans = min(ans, root.val - pre)
                pre = root.val
                root = root.right
        
        return ans