Sponsored
Sponsored
In this approach, we will perform an in-order traversal of the BST using an explicit stack to store the node values in a sorted manner. As we traverse the tree, we will calculate the minimum difference between consecutive values.
Time Complexity: O(N), where N is the number of nodes. Each node is visited exactly once.
Space Complexity: O(H), where H is the height of the tree, representing the maximum size of the stack.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def minDiffInBST(self, root: TreeNode) -> int:
9 stack, prev_value, min_diff = [], None, float('inf')
10 current = root
11
12 while stack or current:
13 while current:
14 stack.append(current)
15 current = current.left
16 current = stack.pop()
17 if prev_value is not None:
18 min_diff = min(min_diff, current.val - prev_value)
19 prev_value = current.val
20 current = current.right
21
22 return min_diff
23The Python solution uses a procedural stack-based in-order traversal to simulate recursive behavior. During the traversal, the minimum absolute difference is calculated between successive node values.
This approach relies on a recursive in-order traversal of the BST to compute the minimum absolute difference. We maintain a global variable to track the smallest difference encountered during traversal.
Time Complexity: O(N)
Space Complexity: O(H), due to recursive call stack.
1#include<limits>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
int minDiff = numeric_limits<int>::max();
int prevValue = -1;
public:
void inOrder(TreeNode* node) {
if (node == nullptr) return;
inOrder(node->left);
if (prevValue >= 0) {
minDiff = min(minDiff, node->val - prevValue);
}
prevValue = node->val;
inOrder(node->right);
}
int minDiffInBST(TreeNode* root) {
prevValue = -1;
minDiff = numeric_limits<int>::max();
inOrder(root);
return minDiff;
}
};
In C++, recursive in-order traversal adjusts a class member as it traverses and computes minimal differences. The method offers a sleek encapsulation of pointer handling, benefiting from C++ class structures.