> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/783.-minimum-distance-between-bst-nodes.md).

# 783. Minimum Distance Between BST Nodes

## 1.問題

![](/files/-LKQGz2qffWIQBhaWVZP)

## 2.想法

* 用In-order traversal遍歷, 並將上一個root以及最小值記錄起來
* 傳遞給function的參數是address

## 3.程式碼

```
/**
 * 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 minVal = INT_MAX;
        int val = -1;
        inOrder(root, val, minVal);
        return minVal;
    }
private:
    void inOrder(TreeNode* root, int& val, int& minVal) {
        if (!root) {
            return;
        }
        
        inOrder(root->left, val, minVal);
        
        if (val > 0) {
            minVal = min(minVal, abs(root->val - val));
        }
        val = root->val;
        
        inOrder(root->right, val, minVal);
    }
};
```

## 4.Performance

![](/files/-LKQHYgJW_yYEVG16ua1)
