您的位置:首页 > 其它

501. Find Mode in Binary Search Tree

2018-01-10 15:48 302 查看
1. Description

Given a BST, find the most frequently occurred element in the BST.

2. Solution

Preorder traverse the BST, and store the value of nodes in a vector.

Find the most common element in the vector.

3. Code

vector<int> findMode(TreeNode* root) {
vector<int> ans;
if(!root)
return ans;
stack<TreeNode*>s;
while(root){
s.push(root);
root = root->left;
}

int cnt = 0;
int a = INT_MAX;
int len = 0;

while(!s.empty()){
TreeNode* curr = s.top();
s.pop();
if(curr->val == a) cnt++;
else{
if(cnt>len){
ans.clear();
ans.push_back(a);
len=cnt;

}
else if(cnt==len){
ans.push_back(a);
}
cnt=1;
a=curr->val;
}
curr=curr->right;
while(curr){
s.push(curr);
curr = curr->left;
}
}
if(cnt>len){
ans.clear();
ans.push_back(a);
}
else if(cnt==len){
ans.push_back(a);
}
return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Tree