LeetCode Find Mode in BST

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Solution 1(菜鸟解法):

vector findMode(TreeNode* root) {
        vector key;
        midTraversal(root, key);
        int maxKey, time = 0;
        int i = 0;
        while(i < key.size()) {
            int tmpTime = 1;
            while(i+1 < key.size() && key[i+1] == key[i]){
                i++;
                tmpTime++;
            }
            if(tmpTime > time){
                maxKey = key[i];
                time = tmpTime;
            }
            i++;
        }
        i = 0;
        int index = 0;
        while(i < key.size()){
            int tmpTime = 1;
            while(i+1 < key.size() && key[i+1] == key[i]){
                i++;
                tmpTime++;
            }
            if(tmpTime == time){
                key[index++] = key[i];
            }
            i++;
        }
        key.erase(key.begin() + index, key.end());
        return key;
    }
    void midTraversal(TreeNode* root, vector& key) {
        if(root == NULL) return;
        midTraversal(root->left, key);
        key.push_back(root->val);
        midTraversal(root->right, key);
    }

思路:递归求出中序遍历数组,然后扫描数组找出最大次数,再求出满足题意的元素。
可以优化成以下解法(无需把中序遍历的次序完整存到数组中,用一个cnt维护)
Solution 2:

vector findMode(TreeNode* root) {
        vector res;
        int cnt = 0;
        TreeNode* pre = NULL;
        int gmax = -1;
        helper(root, res, pre, cnt, gmax);
        return res;
    }
    void helper(TreeNode* root, vector& res, TreeNode*& pre, int& cnt, int& gmax) {
        if(root == NULL) return;
        helper(root->left, res, pre, cnt, gmax);
        if(pre) cnt = (root->val == pre->val) ? cnt+1: 1;
        else cnt = 1;
        if(cnt >= gmax){
            if(cnt > gmax)
                res.clear();
            res.push_back(root->val);
            gmax = cnt;
        }
        pre = root;
        helper(root->right, res, pre, cnt, gmax);
    }

你可能感兴趣的:(LeetCode Find Mode in BST)