教科书式编程:考察BST树中序有序。所以,我们仅仅需要对其中序记住前面一个节点,然后进行比较即可。最后更新ans
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* pre = NULL; int ans = 999999; int getMinimumDifference(TreeNode* root) { inOrder(root); return ans; } void inOrder(TreeNode* root) { if(!root) return; inOrder(root->left); if(pre) ans = min(ans, abs(pre->val - root->val)); pre = root; inOrder(root->right); } };