给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。
/**
* 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 getMinimumDifference(TreeNode* root) {
int m=std::numeric_limits<int>::max();
if(!root) return m;
int ld=m,rd=m;
if(root->left)
{
TreeNode* leftNode=root->left;
while(leftNode)
{
ld=root->val - leftNode->val;
leftNode=leftNode->right;
}
}
if(root->right)
{
TreeNode* rightNode=root->right;
while(rightNode)
{
rd=rightNode->val-root->val;
rightNode=rightNode->left;
}
}
// cout<<ld << " " <<rd << " "<< m<<endl;
if(root->left&& root->right)
{
m=min(ld,rd);
m=min(m,min(getMinimumDifference(root->left),getMinimumDifference(root->right)));
}
else if (root->left)
m=min(ld,getMinimumDifference(root->left));
else if(root->right) m=min(rd,getMinimumDifference(root->right));
else
return m;
// cout<<m<<endl;
return m;
}
};
执行用时 : 40 ms, 在Minimum Absolute Difference in BST的C++提交中击败了86.97% 的用户
内存消耗 : 21.8 MB, 在Minimum Absolute Difference in BST的C++提交中击败了90.12% 的用户