# 530.Minimum Absolute Difference in BST

**530.Minimum Absolute Difference in BST**

难度:Easy

> 给定一个所有节点为非负值的二叉搜索树，求树中任意两节点的差的绝对值的最小值。

示例 :

```
输入:

   1
    \
     3
    /
   2

输出:
1
```

解释: 最小绝对差为1，其中 2 和 1 的差的绝对值为 1（或者 2 和 3）。 注意: 树中至少有2个节点。

递归判断，当前根节点的最小绝对差是与其左子树的最后最右节点的绝对差，和其与右子树的最后最左节点的绝对差的较小值。

```
/**
 * 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% 的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/530.minimum_absolute_difference_in_bst.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
