LeetCode783(2021.4.13)

LC783. 二叉搜索树节点最小距离

class Solution {
public:
    void dfs(TreeNode *root, int &pre, int &ans) {
        if (root == nullptr) {
            return;
        }
        dfs(root->left, pre, ans);
        if (pre == -1) {
            pre = root->val;
        }
        else {
            ans = min(ans, root->val - pre);
            pre = root->val;
        }
        dfs(root->right, pre, ans);
    }

    int minDiffInBST(TreeNode *root) {
        int ans = INT_MAX, pre = -1;
        dfs(root, pre, ans); //中序遍历,维护最小差值
        return ans;
    }
};

发表评论