leetcode

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

1315.cpp (860B)


      1 class Solution {
      2   public:
      3     int sumEvenGrandparent(TreeNode *root) {
      4         stack<TreeNode *> st;
      5         int sum = 0;
      6 
      7         st.push(root);
      8         while (!st.empty()) {
      9             TreeNode *root = st.top();
     10             st.pop();
     11 
     12             if (root->left) {
     13                 st.push(root->left);
     14                 if (root->val % 2 == 0) {
     15                     if (root->left->left) sum += root->left->left->val;
     16                     if (root->left->right) sum += root->left->right->val;
     17                 }
     18             }
     19 
     20             if (root->right) {
     21                 st.push(root->right);
     22                 if (root->val % 2 == 0) {
     23                     if (root->right->left) sum += root->right->left->val;
     24                     if (root->right->right) sum += root->right->right->val;
     25                 }
     26             }
     27         }
     28 
     29         return sum;
     30     }
     31 };