leetcode

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

0112.cpp (593B)


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