leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0501.cpp (897B)
0 class Solution {
1 public:
2 vector<int> findMode(TreeNode *root) {
3 stack<TreeNode *> st;
5 int maxi = INT_MIN, cnt = 0, prev = -1;
6 vector<int> res;
7 while (true) {
8 while (root) {
9 st.push(root);
10 root = root->left;
11 }
12 if (st.empty()) break;
13 root = st.top(), st.pop();
14 if (root->val != prev) {
15 if (cnt >= maxi) {
16 if (cnt > maxi) res.clear();
17 maxi = cnt;
18 res.push_back(prev);
19 }
20 prev = root->val;
21 cnt = 1;
22 } else
23 cnt++;
24 root = root->right;
25 }
26 if (cnt >= maxi) {
27 if (cnt > maxi) res.clear();
28 maxi = cnt;
29 res.push_back(prev);
30 }
31 return res;
32 }
33 };