# 783. Minimum Distance Between BST Nodes

## 1.問題

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKP_al430aDt4QwZfzF%2F-LKQGz2qffWIQBhaWVZP%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8B%E5%8D%882.59.06.png?alt=media\&token=0d675730-ebe3-45b6-9ca3-a95058086f8e)

## 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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKP_al430aDt4QwZfzF%2F-LKQHYgJW_yYEVG16ua1%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8B%E5%8D%882.59.45.png?alt=media\&token=c0796e92-f084-4ff7-8766-ba5de3473521)
