runnig

[leetcode] 112 Path Sum

Feb 4th, 2013
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. /*
  2. http://leetcode.com/onlinejudge#question_112
  3.  
  4. Given a binary tree and a sum,
  5. determine if the tree has a root-to-leaf path such
  6. that adding up all the values along the path equals the given sum.
  7.  
  8. For example:
  9. Given the below binary tree and sum = 22,
  10.               5
  11.              / \
  12.             4   8
  13.            /   / \
  14.           11  13  4
  15.          /  \      \
  16.         7    2      1
  17. return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
  18. */
  19.  
  20. class Solution {
  21. public:
  22.     bool hasPathSum(TreeNode *root, int sum) {
  23.         if(!root) { return false; }      
  24.        
  25.         const int S = sum - root->val;
  26.         if(!root->left && !root->right && 0==S)
  27.         {
  28.             return true;
  29.         }
  30.        
  31.         bool L = hasPathSum(root->left, S);
  32.         if(L) { return true; }
  33.        
  34.         return hasPathSum(root->right, S);
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment