/** * 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: int minDiffInBST(TreeNode* root) { if (root == NULL) return 0; int res = INT_MAX; helper(root, res, NULL); return res; } TreeNode* helper(TreeNode* root, int &res, TreeNode* prev) { if (root->left) { TreeNode* left = helper(root->left, res, prev); res = min(res, root->val - left->val); prev = left; } if (prev) res = min(res, root->val - prev->val); if (root->right) return helper(root->right, res, root); else return root; } };