Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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:
[2, 100]
.0 <= Node.val <= 105
class Solution {
public:
int res = INT_MAX, pre = -1;
int minDiffInBST(TreeNode* root) {
if (root->left != NULL) minDiffInBST(root->left);
if (pre >= 0) res = min(res, root->val - pre);
pre = root->val;
if (root->right != NULL) minDiffInBST(root->right);
return res;
}
};
class Solution {
Integer res = Integer.MAX_VALUE, pre = null;
public int minDiffInBST(TreeNode root) {
if (root.left != null) minDiffInBST(root.left);
if (pre != null) res = Math.min(res, root.val - pre);
pre = root.val;
if (root.right != null) minDiffInBST(root.right);
return res;
}
}
class Solution(object):
pre = -float('inf')
res = float('inf')
def minDiffInBST(self, root):
if root.left:
self.minDiffInBST(root.left)
self.res = min(self.res, root.val - self.pre)
self.pre = root.val
if root.right:
self.minDiffInBST(root.right)
return self.res
In our experience, we suggest you solve this Minimum Distance Between BST Nodes LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Minimum Distance Between BST Nodes LeetCode Solution
I hope this Minimum Distance Between BST Nodes LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>