leetcode

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

1022.cpp (610B)


      1 class Solution {
      2   public:
      3     int sumRootToLeaf(TreeNode *root) {
      4         if (!root) return 0;
      5         stack<pair<TreeNode *, int>> st;
      6         int sum = 0;
      7 
      8         st.push({root, 0});
      9         while (!st.empty()) {
     10             TreeNode *root = st.top().first;
     11             int val = (st.top().second << 1) | root->val;
     12             st.pop();
     13             if (!root->left && !root->right) {
     14                 sum += val;
     15                 continue;
     16             }
     17             if (root->left) st.push({root->left, val});
     18             if (root->right) st.push({root->right, val});
     19         }
     20         return sum;
     21     }
     22 };