0501.cpp (897B)
1 class Solution { 2 public: 3 vector<int> findMode(TreeNode *root) { 4 stack<TreeNode *> st; 5 6 int maxi = INT_MIN, cnt = 0, prev = -1; 7 vector<int> res; 8 while (true) { 9 while (root) { 10 st.push(root); 11 root = root->left; 12 } 13 if (st.empty()) break; 14 root = st.top(), st.pop(); 15 if (root->val != prev) { 16 if (cnt >= maxi) { 17 if (cnt > maxi) res.clear(); 18 maxi = cnt; 19 res.push_back(prev); 20 } 21 prev = root->val; 22 cnt = 1; 23 } else 24 cnt++; 25 root = root->right; 26 } 27 if (cnt >= maxi) { 28 if (cnt > maxi) res.clear(); 29 maxi = cnt; 30 res.push_back(prev); 31 } 32 return res; 33 } 34 };