Leetcode 799 Solution

This article provides solution to leetcode question 799 (minimum-distance-between-bst-nodes)

https://leetcode.com/problems/minimum-distance-between-bst-nodes

Solution

/**
 * 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 {
    int ans;

public:
    pair<int, int> _minDiffInBST(TreeNode* root) {
        int val = root->val;

        pair<int, int> left_res = make_pair(val, val);
        if (root->left)
        {
            left_res = _minDiffInBST(root->left);
            ans = min(ans, val - left_res.second);
        }

        pair<int, int> right_res = make_pair(val, val);
        if (root->right)
        {
            right_res = _minDiffInBST(root->right);
            ans = min(ans, right_res.first - val);
        }

        return make_pair(left_res.first, right_res.second);
    }

    int minDiffInBST(TreeNode* root) {
        ans = INT_MAX;
        _minDiffInBST(root);
        return ans;
    }
};