# 783.Minimum Distance Between BST Nodes

**783.Minimum Distance Between BST Nodes**

难度:Easy

> 给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。

示例：

```
输入: root = [4,2,6,1,3,null,null]
输出: 1
解释:
注意，root是树结点对象(TreeNode object)，而不是数组。

给定的树 [4,2,6,1,3,null,null] 可表示为下图:

          4
        /   \
      2      6
     / \    
    1   3  

最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。
```

注意：

二叉树的大小范围在 2 到 100。 二叉树总是有效的，每个节点的值都是整数，且不重复。

对于一个根节点，最小距离是与其左子树最右后继节点的距离和其与右子树最左后继节点的距离的较小值。然后递归判断。

```
/**
 * 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) {
        int res;
        if(!root) return INT_MAX;
        if(!root->left && !root->right) return INT_MAX;
        
        TreeNode* lm;
        TreeNode* rm;
        if(root->left)
        {
            lm=root->left;
        while(lm->right)
            lm=lm->right;
        }
        if(root->right){
            rm=root->right;
        while(rm->left)
            rm=rm->left;
        }
        if(root->left && root->right)
            res=min(root->val- lm->val, rm->val -root->val);
        else if(root->left)
            res=root->val-lm->val;
        else
            res=rm->val -root->val;
        if(root->left)
            res=min(res, minDiffInBST(root->left));
        if(root->right) 
            res=min(res,minDiffInBST(root->right));
        return res;
    }
};
```

> 执行用时 : 4 ms, 在Minimum Distance Between BST Nodes的C++提交中击败了97.57% 的用户\
> 内存消耗 : 11.4 MB, 在Minimum Distance Between BST Nodes的C++提交中击败了50.42% 的用户


---

# 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/783.minimum_distance_between_bst_nodes.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.
