783. Minimum Distance Between BST Nodes

Posted jtechroad

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了783. Minimum Distance Between BST Nodes相关的知识,希望对你有一定的参考价值。

/**
 * 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) {
        if (root == NULL)
            return 0;
        int res = INT_MAX;
        helper(root, res, NULL);
        return res;
    }
    TreeNode* helper(TreeNode* root, int &res, TreeNode* prev) {
        if (root->left) {
            TreeNode* left = helper(root->left, res, prev);
            res = min(res, root->val - left->val);
            prev = left;
        }
        
        if (prev)
            res = min(res, root->val - prev->val);
        
        if (root->right)
            return helper(root->right, res, root);
        else
            return root;
    }
};

 

以上是关于783. Minimum Distance Between BST Nodes的主要内容,如果未能解决你的问题,请参考以下文章

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Node

[leetcode-783-Minimum Distance Between BST Nodes]

783. Minimum Distance Between BST Nodes - Easy