Sponsored
Sponsored
An inorder traversal of a BST yields nodes in non-decreasing order. By performing an inorder traversal, we can collect the values of the nodes in a sorted manner and then iterate through these values to find the minimum difference between successive nodes.
Time Complexity: O(N), where N is the number of nodes in the tree since we visit each node exactly once.
Space Complexity: O(H) due to the recursion stack, where H is the height of the tree.
1class Solution:
2 def __init__(self):
3 self.min_diff = float('inf')
4 self.prev = None
5
6 def minDiffInBST(self, root):
7 self.inorder(root)
8 return self.min_diff
9
10 def inorder(self, node):
11 if not node:
12 return
13 self.inorder(node.left)
14 if self.prev is not None:
15 self.min_diff = min(self.min_diff, node.val - self.prev)
16 self.prev = node.val
17 self.inorder(node.right)
Here, we store the minimum difference and the previous node value as instance variables. As we traverse the tree using inorder, we update these instance variables to compute the minimum difference.
The Morris Traversal is an inorder tree traversal technique that uses constant space by reusing the tree structure. It involves temporarily rearranging the tree to allow traversal without explicit stack use.
Time Complexity: O(N) where each edge is traversed at most twice, once down and once up.
Space Complexity: O(1) because it does not use stack or recursion.
1#include <climits>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int minDiffInBST(TreeNode* root) {
int minDiff = INT_MAX;
int prev = -1;
TreeNode* curr = root;
while (curr) {
if (!curr->left) {
if (prev != -1) {
minDiff = min(minDiff, curr->val - prev);
}
prev = curr->val;
curr = curr->right;
} else {
TreeNode* pred = curr->left;
while (pred->right && pred->right != curr) {
pred = pred->right;
}
if (!pred->right) {
pred->right = curr;
curr = curr->left;
} else {
pred->right = NULL;
if (prev != -1) {
minDiff = min(minDiff, curr->val - prev);
}
prev = curr->val;
curr = curr->right;
}
}
}
return minDiff;
}
C++ solution uses the same approach with C-style logic tailored for C++ syntax. Temporary threading pointers help visit nodes without stack or recursion, preserving O(1) space complexity.