783. Minimum Distance Between BST Nodes LeetCode Solution
In this guide, you will get 783. Minimum Distance Between BST Nodes LeetCode Solution with the best time and space complexity. The solution to Minimum Distance Between BST Nodes problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Minimum Distance Between BST Nodes solution in C++
- Minimum Distance Between BST Nodes solution in Java
- Minimum Distance Between BST Nodes solution in Python
- Additional Resources
Problem Statement of Minimum Distance Between BST Nodes
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 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 100].
0 <= Node.val <= 105
Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(\log n) \to O(n)
783. Minimum Distance Between BST Nodes LeetCode Solution in C++
class Solution {
public:
int minDiffInBST(TreeNode* root) {
int ans = INT_MAX;
inorder(root, ans);
return ans;
}
private:
int pred = -1;
void inorder(TreeNode* root, int& ans) {
if (root == nullptr)
return;
inorder(root->left, ans);
if (pred >= 0)
ans = min(ans, root->val - pred);
pred = root->val;
inorder(root->right, ans);
}
};
/* code provided by PROGIEZ */
783. Minimum Distance Between BST Nodes LeetCode Solution in Java
class Solution {
public int minDiffInBST(TreeNode root) {
inorder(root);
return ans;
}
private int ans = Integer.MAX_VALUE;
private Integer pred = null;
private void inorder(TreeNode root) {
if (root == null)
return;
inorder(root.left);
if (pred != null)
ans = Math.min(ans, root.val - pred);
pred = root.val;
inorder(root.right);
}
}
// code provided by PROGIEZ
783. Minimum Distance Between BST Nodes LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.