EasyNo. 0783
Minimum Distance Between BST Nodes — LeetCode 783 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example
- Input
- root = [4,2,6,1,3]
- Output
- 1
Python solution
# 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: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]):
if root is None:
return
dfs(root.left)
nonlocal pre, ans
ans = min(ans, root.val - pre)
pre = root.val
dfs(root.right)
pre = -inf
ans = inf
dfs(root)
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 783. Minimum Distance Between BST Nodes is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0449 | Serialize and Deserialize BST | Medium |
| 0530 | Minimum Absolute Difference in BST | Easy |
| 0098 | Validate Binary Search Tree | Medium |
| 0099 | Recover Binary Search Tree | Medium |
| 0100 | Same Tree | Easy |
| 0101 | Symmetric Tree | Easy |
Frequently asked questions
- How hard is LeetCode 783. Minimum Distance Between BST Nodes?
LeetCode 783. Minimum Distance Between BST Nodes is rated Easy on LeetCode.
- What is the time complexity of LeetCode 783. Minimum Distance Between BST Nodes?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 783. Minimum Distance Between BST Nodes?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 783. Minimum Distance Between BST Nodes cover?
LeetCode 783. Minimum Distance Between BST Nodes is tagged Tree, Depth-First Search, Breadth-First Search, Binary Search Tree and Binary Tree on LeetCode.