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.
1public class Solution {
2 private int minDiff = int.MaxValue;
3 private int? prev = null;
4
5 public int MinDiffInBST(TreeNode root) {
6 Inorder(root);
7 return minDiff;
8 }
9
10 private void Inorder(TreeNode node) {
11 if (node == null) return;
12 Inorder(node.left);
13 if (prev.HasValue) {
14 minDiff = Math.Min(minDiff, node.val - prev.Value);
15 }
16 prev = node.val;
17 Inorder(node.right);
18 }
19}
The solution uses a nullable integer for prev
to accommodate the absence of a previous value at the start. The method traverses the tree inorder, updating minDiff
accordingly.
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.