-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path501.cpp
47 lines (46 loc) · 990 Bytes
/
501.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
// inOrderTraversal.cpp
/**
* 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 {
vector<int> result;
int curCount = 0;
int maxCount = 0;
int lastValue;
bool firstTime = 1;
public:
vector<int> findMode(TreeNode *root) {
inOrder(root);
return result;
}
void inOrder(TreeNode *root) {
if (root == NULL)
return;
inOrder(root->left);
if (firstTime) {
lastValue = root->val;
firstTime = 0;
}
if (lastValue != root->val) {
curCount = 0;
lastValue = root->val;
}
if (lastValue == root->val) {
++curCount;
if (curCount == maxCount) {
result.push_back(lastValue);
} else if (curCount > maxCount) {
maxCount = curCount;
result.clear();
result.push_back(lastValue);
}
}
inOrder(root->right);
}
};