Path Sum

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:bool flag;
public:
    bool hasPathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        flag = false;
        if(root==NULL)
        return false;
        path(root,sum,0);
        return flag;
    }
    void path(TreeNode *root,int sum, int pre)
    {
        if(root->left==NULL&&root->right==NULL)
        {
            if(pre+root->val==sum)
            flag = true;
        }
        pre = pre+root->val;
        if(root->left!=NULL)
        {
            path(root->left,sum,pre);
        }
        if(root->right!=NULL)
        {
            path(root->right,sum,pre);
        }
    }
};

 

posted on 2013-09-23 00:55  邪灵天使  阅读(161)  评论(0编辑  收藏  举报