給定一棵二元搜尋樹,請找出任意兩個節點之間的最小絕對差值。
這道題的特點是利用 BST 的性質:中序遍歷 的結果會是一個遞增的序列。因此,最小差值一定出現在相鄰節點之間。
實作:
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
int minDiff = INT_MAX;
int prev = -1;
inorderTraversal(root, prev, minDiff);
return minDiff;
}
private:
void inorderTraversal(TreeNode* node, int& prev, int& minDiff) {
if (node == nullptr) return;
inorderTraversal(node->left, prev, minDiff);
if (prev != -1) {
minDiff = std::min(minDiff, node->val - prev);
}
prev = node->val;
inorderTraversal(node->right, prev, minDiff);
}
};
參考:
#530. Minimum Absolute Difference in BST