每日力扣-树-二叉搜索树节点最小距离

67 阅读1分钟

给定一个二叉搜索树的根节点 root,返回树中任意两节点的差的最小值。

解题思路:因为是二叉搜索树,任意两点最小值一定是相邻的,使用dfs遍历

class Solution {
public:
    int m = INT_MAX;
    TreeNode* pre = nullptr;
    int minDiffInBST(TreeNode* root) {
        dfs(root);
        return m;
    }
    void dfs(TreeNode* cur)
    {
        if(cur == nullptr) return;
        dfs(cur->left);
        if(pre != nullptr)
        {
            m = min(m,cur->val - pre->val);
        }
        pre = cur;
        dfs(cur->right);
    }
};