783. Minimum Distance Between BST Nodes

时间:2021-10-14 23:20:28

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

/**
 * 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 res = INT_MAX;
    int minDiffInBST(TreeNode* root) {
        dfs(root);
        return res;
    }
    TreeNode* dfs(TreeNode* root, TreeNode* pre = NULL) {
        if (root == NULL)
            return NULL;
        
        if (root->left) {
            TreeNode* leftLast = dfs(root->left, pre);
            res = min(res, root->val - leftLast->val);
        }
        else if (pre != NULL) {
            res = min(res, root->val - pre->val);
        }
        
        if (root->right) {
            return dfs(root->right, root);
        }
        return root;
    }
};