1. 中序遍历
看到二叉搜索树优先考虑“二叉搜索树的中序序列是递增的”。
获取中序序列后两两比较差值。
时间O(n)
,空间O(n)
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class Solution { public: int getMinimumDifference(TreeNode* root) { vector<int> nums; stack<TreeNode*> st;
while (root != nullptr || !st.empty()) { if (root == nullptr) { TreeNode* temp = st.top(); st.pop(); nums.push_back(temp->val); root = temp->right; } else { st.push(root); root = root->left; } }
int ans = INT_MAX, n = nums.size(); for (int i = 1; i < n; i++) ans = min(ans, nums[i] - nums[i - 1]); return ans; } };
|