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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <limits.h>
4
5struct TreeNode {
6 int val;
7 struct TreeNode *left;
8 struct TreeNode *right;
9};
10
11void inorder(struct TreeNode* root, int* prev, int* minDiff) {
12 if (!root) return;
13 inorder(root->left, prev, minDiff);
14 if (*prev != -1) {
15 int diff = root->val - *prev;
16 if (diff < *minDiff) {
17 *minDiff = diff;
18 }
19 }
20 *prev = root->val;
21 inorder(root->right, prev, minDiff);
22}
23
24int minDiffInBST(struct TreeNode* root) {
25 int minDiff = INT_MAX;
26 int prev = -1;
27 inorder(root, &prev, &minDiff);
28 return minDiff;
29}
This solution performs an inorder traversal of the tree. We keep track of the previous node value and calculate the difference between the current node and the previous node. We update the minimum difference 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
Python implementation applies Morris Traversal for an efficient in-order walk, using tree pointers for thread simulation rather than auxiliary space.