forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s2.cpp
51 lines (50 loc) · 1.17 KB
/
s2.cpp
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
41
42
43
44
45
46
47
48
49
50
51
// https://discuss.leetcode.com/topic/77335/proper-o-1-space
/**
* 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 {
private:
void handleVal(int val) {
if (val != currVal) {
currVal = val;
currCount = 0;
}
++currCount;
if (currCount > maxCount) {
maxCount = currCount;
modeCount = 1;
} else if (currCount == maxCount) {
if (collect) {
modes.push_back(currVal);
}
++modeCount;
}
}
void traverse(TreeNode *root) {
if (!root) return;
traverse(root->left);
handleVal(root->val);
traverse(root->right);
}
vector<int> modes;
int modeCount = 0;
int currCount = 0;
int currVal = 0;
int maxCount = 0;
bool collect = false;
public:
vector<int> findMode(TreeNode* root) {
traverse(root);
modeCount = 0;
currCount = 0;
collect = true;
traverse(root);
return modes;
}
};