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 int minDiff = Integer.MAX_VALUE;
3 Integer prev = null;
4
5 public int minDiffInBST(TreeNode root) {
6 inorder(root);
7 return minDiff;
8 }
9
10 public void inorder(TreeNode node) {
11 if (node == null) return;
12 inorder(node.left);
13 if (prev != null) {
14 minDiff = Math.min(minDiff, node.val - prev);
15 }
16 prev = node.val;
17 inorder(node.right);
18 }
19}
In this Java solution, we use an Integer wrapper for the prev
variable in order to handle null values more cleanly. The core logic remains the same as other implementations.
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.