Minimum Absolute Difference in BST && Find Mode in Binary Search Tree

Minimum Absolute Difference in BST的思路就是BST中序遍历,得到的就是从小到大排的顺序,然后依次算两个的差,就能得到最小值

/**
 * 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 minre = INT_MAX;
    TreeNode *prev=NULL;
    int getMinimumDifference(TreeNode* root) {
        if(root==NULL)
        return minre;
        getMinimumDifference(root->left);
        if(prev!=NULL)
        {
            minre=min(minre,root->val-prev->val);
        }
        prev=root;
        getMinimumDifference(root->right);
        return minre;
    }
   
};


Find Mode in Binary Search Tree的道理也是一样的,还是中序遍历,然后算每个数出现了几次,找到出现次数最多的(用一个Count和CurrentCount,一个计算目前出现过的最大次数,另一个算当前数字出现的次数,两个比)

/**
 * 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:
    vector<int> re;
    int count=1;
    int currentCount=1;
    TreeNode *prev=NULL;
    vector<int> findMode(TreeNode* root) {
        if(root==NULL)
        return re;
        
        findMode(root->left);
        if(prev!=NULL)
        {
            if(root->val==prev->val)
            {
                currentCount++;
                if(currentCount==count)
                {
                    re.push_back(prev->val);
                }
                else if(currentCount>count)
                {
                    re.clear();
                    re.push_back(prev->val);
                    count=currentCount;
                }
            }
            else
            {
                currentCount=1;
                
            }
        }
        prev=root;
        if(count==1)
            {
            re.push_back(root->val);
            }
        findMode(root->right);
        return re;
        
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章