LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)
题意:寻找二叉查找树中出现次数最多的值
/**
* 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 ma = 0;
int cnt = 1;
TreeNode *pre = NULL;
vector<int> ans;
void inorder(TreeNode* root){
if(root == NULL) return;
inorder(root -> left);
if(pre){
if(pre -> val == root -> val){
++cnt;
}
else{
if(cnt > ma){
ma = cnt;
ans.clear();
ans.push_back(pre -> val);
}
else if(cnt == ma){
ans.push_back(pre -> val);
}
cnt = 1;
}
}
pre = root;
inorder(root -> right);
}
vector<int> findMode(TreeNode* root) {
if(root == NULL) return ans;
inorder(root);
if(cnt > ma){
ans.clear();
ans.push_back(pre -> val);
}
else if(cnt == ma){
ans.push_back(pre -> val);
}
return ans;
}
};

浙公网安备 33010602011771号