Minimum Absolute Difference in BST – LeetCode 530
Problem
Description
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Answer
Original
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class Solution { int min_dif = INT_MAX, val = -1; public: int getMinimumDifference(TreeNode* root) { if (root->left != NULL) getMinimumDifference(root->left); if (val >= 0) min_dif = min(min_dif, root->val - val); val = root->val; if (root->right != NULL) getMinimumDifference(root->right); return min_dif; } };
|
思路
遍历节点,计算临近节点值的最小差即可。时间复杂度$O(n)$,空间复杂度$O(log{n})$。
耗时$22$ ms,排名$11.39\%$
Better
思路
还没看到更好的思路。