forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-mode-in-binary-search-tree.cpp
51 lines (47 loc) · 1.23 KB
/
find-mode-in-binary-search-tree.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
// Time: O(n)
// Space: O(h)
/**
* 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) {
if (!root) {
return {};
}
vector<int> result;
TreeNode *prev = nullptr;
int cnt = 1, max_cnt = 0;
inorder(root, &prev, &cnt, &max_cnt, &result);
return result;
}
private:
void inorder(TreeNode *root, TreeNode **prev, int *cnt, int *max_cnt, vector<int> *result) {
if (root == nullptr) {
return;
}
inorder(root->left, prev, cnt, max_cnt, result);
if (*prev) {
if (root->val == (*prev)->val) {
++(*cnt);
} else {
*cnt = 1;
}
}
if (*cnt > *max_cnt) {
*max_cnt = *cnt;
result->clear();
result->emplace_back(root->val);
} else if (*cnt == *max_cnt) {
result->emplace_back(root->val);
}
*prev = root;
inorder(root->right, prev, cnt, max_cnt, result);
}
};