530. 二叉搜索树的最小绝对差
一、二叉搜索树性质
二叉搜索树的中序遍历为升序,将树遍历成数组,再对数组进行求差值
二、优化
在遍历的过程中进行计算差值
因为二叉搜索树的中序遍历为升序,所以最小绝对差肯定出现在相邻的两个结点中
用pre记录前一节点,
class Solution {public:TreeNode* pre=NULL;int result = INT_MAX;void dfs(TreeNode* cur){if(!cur)return;dfs(cur->left);if(pre!=NULL)result = min(result,cur->val-pre->val);pre = cur;dfs(cur->right);}int getMinimumDifference(TreeNode* root) {dfs(root);return result;}};
