leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0508.cpp (969B)
0 class Solution {
1 public:
2 vector<int> findFrequentTreeSum(TreeNode *root) {
3 unordered_map<int, int> um;
4 stack<TreeNode *> st({root});
5 while (!st.empty()) {
6 TreeNode *root = st.top();
7 if (root) {
8 st.push(nullptr);
9 if (root->left) st.push(root->left);
10 if (root->right) st.push(root->right);
11 continue;
12 }
13 st.pop();
14 root = st.top();
15 st.pop();
16 if (root->left) root->val += root->left->val;
17 if (root->right) root->val += root->right->val;
18 um[root->val]++;
19 }
21 vector<int> res;
22 int maxi = 0;
23 for (const auto [k, v] : um) {
24 if (v < maxi) continue;
25 if (v == maxi)
26 res.push_back(k);
27 else {
28 maxi = v;
29 res = {k};
30 }
31 }
32 return res;
33 }
34 };