-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindModeInBST.cpp
More file actions
40 lines (40 loc) · 930 Bytes
/
findModeInBST.cpp
File metadata and controls
40 lines (40 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 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> findMode(TreeNode* root) {
vector<int> res;
if (!root) return res;
inorder(root,res);
return res;
}
void inorder(TreeNode* root,vector<int>& res){
if (!root) return;
inorder(root->left,res);
if (!prev || root->val != prev->val){
prev = root;
count = 1;
}
else count++;
if (max < count){
max = count;
res.clear();
res.push_back(root->val);
}
else if ( max == count){
res.push_back(root->val);
}
inorder(root->right,res);
}
private:
int max = 0;
int count = 0;
TreeNode* prev = NULL;
};