leetcode501+BST中出现的数字数目最多的数字,依据中序遍历的性质

https://leetcode.com/problems/find-mode-in-binary-search-tree/description/

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<int> result;
    int maxcount = 0, currentVal = 0, tempCount = 0;
    void inorder(TreeNode* root)
    {
        if(root == NULL) return;
        inorder(root->left);
        tempCount += 1;
        if(root->val != currentVal){ //这个if必须摆在第一位
            currentVal = root->val;
            tempCount = 1;
        }
        if(tempCount > maxcount){
            maxcount = tempCount;
            result.clear();
            result.push_back(root->val);
        }
        else if(tempCount == maxcount){
            result.push_back(root->val);
        }
        inorder(root->right);
    }
    vector<int> findMode(TreeNode* root) {
        inorder(root);
        return result;
    }
};


版权声明:本文为u013554860原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。