LeetCode 783: Minimum Distance Between BST Nodes Solution
Master LeetCode problem 783 (Minimum Distance Between BST Nodes), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
783. Minimum Distance Between BST Nodes
Problem Explanation
Explanation
To find the minimum difference between values of any two different nodes in a BST, we can perform an in-order traversal of the tree and keep track of the previous node's value. As we traverse the tree in-order, we compare the current node's value with the previous node's value and calculate the minimum difference. We update the minimum difference whenever we find a smaller one.
Algorithm:
- Perform an in-order traversal of the BST.
- Keep track of the previous node's value.
- Calculate the difference between the current node's value and the previous node's value.
- Update the minimum difference if a smaller difference is found.
Time complexity: O(n) where n is the number of nodes in the BST.
Space complexity: O(h) where h is the height of the BST.
Solution Code
class Solution {
Integer prev;
int minDiff = Integer.MAX_VALUE;
public int minDiffInBST(TreeNode root) {
inorder(root);
return minDiff;
}
private void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
if (prev != null) {
minDiff = Math.min(minDiff, node.val - prev);
}
prev = node.val;
inorder(node.right);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 783 (Minimum Distance Between BST Nodes)?
This page provides optimized solutions for LeetCode problem 783 (Minimum Distance Between BST Nodes) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 783 (Minimum Distance Between BST Nodes)?
The time complexity for LeetCode 783 (Minimum Distance Between BST Nodes) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 783 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 783 in Java, C++, or Python.