
Problem Statement
In the given problem, we are provided with the root of a Binary Search Tree (BST) and are required to compute the minimum absolute difference between the values of any two different nodes within the tree. The task is to efficiently navigate through the BST, which inherently has its elements sorted according to BST properties, and find the smallest absolute difference possible between any pair of nodes.
Examples
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, 104]
. 0 <= Node.val <= 105
Approach and Intuition
How to Solve the Problem:
Understanding BST Properties:
- In a Binary Search Tree, for any given node, the left subtree contains only nodes with values lesser than the node's value, and the right subtree only nodes with values greater.
- This property provides a natural sorting of elements which can be leveraged by using in-order traversal to access the nodes in sorted order.
Utilizing In-order Traversal:
- By performing an in-order traversal on the BST, we retrieve the node values in non-decreasing order.
- This means that the smallest absolute difference will be between consecutive elements in this traversal order.
Calculating Minimum Difference:
- While performing in-order traversal, keep track of the previous node value.
- For each current node during the traversal, calculate the difference between the current node value and the previous node value.
- Update the minimum difference found so far with this calculated difference if it's smaller.
Examples and Application:
- From Example 1:
- The in-order traversal of the tree
[4, 2, 6, 1, 3]
yields the values[1, 2, 3, 4, 6]
. - The smallest difference here is between consecutive values
3
and4
(or1
and2
, or2
and3
), each providing a difference of1
.
- The in-order traversal of the tree
- From Example 2:
- The in-order traversal of the tree
[1, 0, 48, null, null, 12, 49]
results in[0, 1, 12, 48, 49]
. - Again,
1 - 0
and49 - 48
each provide the smallest difference, which is1
.
- The in-order traversal of the tree
Constraints to consider:
- The tree will have at least two nodes, guaranteeing that there is at least one valid answer.
- Node values are non-negative and can be quite large, up to
105
, but this should not affect the algorithm since only differences are taken into account.
Using the above approach provides a direct and efficient method leveraging the properties of in-order traversal in a BST to find the minimum absolute difference between any two nodes in the tree. This solution operates in O(n) time complexity since each node is visited precisely once during the in-order traversal.
Solutions
- C++
- Java
- Python
class Solution {
public:
int smallestDiff = INT_MAX;
TreeNode* lastVisited = nullptr;
void inOrder(TreeNode* current) {
if (!current) return;
inOrder(current->left);
if (lastVisited != nullptr) {
smallestDiff = min(smallestDiff, current->val - lastVisited->val);
}
lastVisited = current;
inOrder(current->right);
}
int findMinDiff(TreeNode* root) {
inOrder(root);
return smallestDiff;
}
};
The solution presented in C++ aims to find the minimum absolute difference between the values of any two nodes in a Binary Search Tree (BST). This approach effectively leverages the properties of BST and in-order traversal to solve the problem with a high degree of efficiency.
** Key elements of the solution include: **
Definition of two private members in the Solution class:
- An integer,
smallestDiff
, initialized toINT_MAX
to store the minimum difference. - A
TreeNode
pointer,lastVisited
, initialized tonullptr
to keep track of the last node visited during the in-order traversal.
- An integer,
The
inOrder
function is a recursive method that:- Terminates the recursive call if the current node is
nullptr
. - Performs a leftward traversal (visit left subtree).
- Updates the
smallestDiff
using the value of the current node and the value oflastVisited
iflastVisited
is notnullptr
. - Moves the
lastVisited
pointer to the current node. - Proceeds to rightward traversal (visit right subtree).
- Terminates the recursive call if the current node is
The
findMinDiff
function:- Initiates the in-order traversal from the root.
- Returns the
smallestDiff
as the result after completing the traversal.
This solution benefits from the sorted nature of the BST, where an in-order traversal yields values in a non-decreasing order. By checking consecutive elements during this traversal, it efficiently pinpoint the smallest difference without the need for comparing every pair of nodes.
class Solution {
int smallestDiff = Integer.MAX_VALUE;
TreeNode previous;
void traverseInOrder(TreeNode current) {
if (current == null) {
return;
}
traverseInOrder(current.left);
if (previous != null) {
smallestDiff = Math.min(smallestDiff, current.val - previous.val);
}
previous = current;
traverseInOrder(current.right);
}
int findMinDiff(TreeNode root) {
traverseInOrder(root);
return smallestDiff;
}
};
The provided Java program solves the problem of finding the minimum absolute difference between the values of any two nodes in a Binary Search Tree (BST). The solution utilizes an in-order traversal to explore the BST and hence leverages the property of BST where in-order traversal leads to values being accessed in ascending order. Below are the core components and steps of the solution:
A class named
Solution
is defined with two instance variables:smallestDiff
is initialized toInteger.MAX_VALUE
to ensure that any smaller difference found during traversal will be updated.previous
is aTreeNode
object used to keep track of the previously visited node during the in-order traversal.
The
traverseInOrder
method is a recursive function:- It accepts a
TreeNode
object representing the current node to be processed. - Base case: If the current node is null, the function returns immediately, aiding in navigating leaf nodes.
- Firstly, the method recursively calls itself on the left child of the current node, ensuring traversal of the tree from the smallest value up.
- A comparison is conducted (if there’s a
previous
node) to determine the difference between the current and previous node values. ThesmallestDiff
is updated if the new found difference is smaller. - The
previous
node is then updated to the current node before a recursive call is made to the right child, continuing the in-order traversal.
- It accepts a
The
findMinDiff
method facilitates the process:- Initiates the traversal from the root of the BST.
- It returns the
smallestDiff
after the traversal completes, which is the minimum absolute difference found between any nodes in the BST.
Ensure you replace the TreeNode
class usage above with an appropriate implementation or definition of the TreeNode
as per your existing data structures or frameworks. This code snippet assumes such a class is predefined with at least two member variables: val
(value of the node), left
and right
(pointers to child nodes).
class Solution:
def findMinDiffInBST(self, node: Optional[TreeNode]) -> int:
self.smallestGap = float('inf')
self.lastValue = None
def traverse_in_order(current):
if current is None:
return
traverse_in_order(current.left)
if self.lastValue is not None:
self.smallestGap = min(self.smallestGap, current.val - self.lastValue)
self.lastValue = current.val
traverse_in_order(current.right)
traverse_in_order(node)
return self.smallestGap
The given solution focuses on finding the minimum absolute difference between any two nodes' values in a Binary Search Tree (BST). The solution employs an in-order traversal, which inherently accesses the BST nodes in an ascending order. Here's a breakdown of the approach:
- A helper function
traverse_in_order
is defined to perform the in-order traversal of the BST. - During the traversal, the difference between every two consecutive nodes is computed.
self.lastValue
holds the value of the previously visited node, ensuring that the difference is calculated between consecutive nodes when traversing. - The minimum difference
self.smallestGap
is updated continuously during the traversal whenever a smaller gap is found.
Key aspects of the implementation include:
- Using a class variable
self.lastValue
to keep track of the last node's value during the in-order traversal. - Another class variable
self.smallestGap
is used to store the minimum difference found during traversal. This is initialized to infinity (float('inf')
) so that any found difference will be smaller initially. - Starting the traversal from the root node, the function
traverse_in_order
is first called.
This method efficiently finds the minimum absolute difference by leveraging the properties of BST and in-order traversal, ensuring a time complexity of O(n) with n being the number of nodes in the BST, since each node is visited exactly once.
No comments yet.