Minimum Difference Between BST Nodes(C++ LintCode)

解题思路:

(1)使用set,保存所有的结点值

(2)因为set会自动排序,此时只需要比较相邻的差值即可

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
    private:
        set<int> myset;
    public:
        /**
         * @param root: the root
         * @return: the minimum difference between the values of any two different nodes in the tree
         */
        int minDiffInBST(TreeNode * root) {
            // Write your code here
            pre_tree(root);
            int min = root->val;
            set<int>::iterator p=myset.begin(),q=next(p,1);
            for(;q!=myset.end();p++,q++) {
                if (*q-*p<min) min = *q-*p;
            }
            return min;
        }
        
        void pre_tree(TreeNode *root) {
            if (root) {
                myset.insert(root->val);
                pre_tree(root->left);
                pre_tree(root->right);
            }
        }
};
发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105651735