leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0508.cpp (969B)


      1 class Solution {
      2   public:
      3     vector<int> findFrequentTreeSum(TreeNode *root) {
      4         unordered_map<int, int> um;
      5         stack<TreeNode *> st({root});
      6         while (!st.empty()) {
      7             TreeNode *root = st.top();
      8             if (root) {
      9                 st.push(nullptr);
     10                 if (root->left) st.push(root->left);
     11                 if (root->right) st.push(root->right);
     12                 continue;
     13             }
     14             st.pop();
     15             root = st.top();
     16             st.pop();
     17             if (root->left) root->val += root->left->val;
     18             if (root->right) root->val += root->right->val;
     19             um[root->val]++;
     20         }
     21 
     22         vector<int> res;
     23         int maxi = 0;
     24         for (const auto [k, v] : um) {
     25             if (v < maxi) continue;
     26             if (v == maxi)
     27                 res.push_back(k);
     28             else {
     29                 maxi = v;
     30                 res = {k};
     31             }
     32         }
     33         return res;
     34     }
     35 };