【leetcode】Path Sum

来源:互联网 发布:2016 fc2视频最新域名 编辑:程序博客网 时间:2024/06/05 16:28
/** * 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 recursive(TreeNode *cur,int sum,int tmpSum)    {        if(cur->left==NULL&&cur->right==NULL)//叶子节点        {               if(tmpSum==sum)                return true;            else                 return false;        }                bool lefCheck=false,rigCheck=false;        if(cur->left!=NULL)            lefCheck=recursive(cur->left,sum,tmpSum+(cur->left->val));        if(cur->right!=NULL)            rigCheck=recursive(cur->right,sum,tmpSum+(cur->right->val));        return lefCheck||rigCheck;    }    bool hasPathSum(TreeNode *root, int sum) {        // Note: The Solution object is instantiated only once and is reused by each test case.        if(root==NULL)            return false;        return recursive(root,sum,root->val);    }};

原创粉丝点击