问题描述
给定一个二叉搜索树的根节点 root,返回树中任意两节点的差的最小值。
解题报告
像中序遍历二叉搜索树,得到递增的序列这种方法暂且不考虑,只考虑递归。
整棵树中任意两节点的差的最小值有三种取值可能:
- 根节点与其他节点的差值的最小值,即根节点与左子树中最大值的差值和右子树中的最小值与根节点的差值中的较小者;
- 根节点的左子树中任意两节点的差的最小值;
- 根节点的右子树中任意两节点的差的最小值;
实现代码
/**
* 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 helper(TreeNode* root, int flag){
if(flag){
while(root->right) root=root->right;
}
else{
while(root->left) root=root->left;
}
return root->val;
}
int minDiffInBST(TreeNode* root){
if(root==NULL)return INT_MAX;
int mid=INT_MAX;
if(root->left!=NULL)mid=root->val-helper(root->left,1);
if(root->right!=NULL)mid=min(mid, helper(root->right,0)-root->val);
int left=minDiffInBST(root->left);
int right=minDiffInBST(root->right);
return min(mid, min(left, right));
}
};