首页 > 代码库 > Leetcode Path Sum

Leetcode Path Sum

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 /**
 * https://oj.leetcode.com/problems/path-sum/
 * 参考http://www.cnblogs.com/remlostime/archive/2012/11/13/2767746.html
 */
 

 
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        return hasSum(root, sum, 0);
    }
    
    bool hasSum(TreeNode *node, int sum, int curSum){
        
        if(node == NULL){
            return false;
        }
        
        if(!node->left && !node->right){
            return (sum == curSum + node->val);
        }
        
        return hasSum(node->left, sum, curSum + node->val) || hasSum(node->right, sum, curSum + node->val);
    }
};

Leetcode Path Sum