首页 > 代码库 > Path Sum

Path Sum

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int indicator = 0;
public:
    void check(TreeNode *root, int sum) {
        if(root == NULL)
            return;
        if(root->left == NULL && root->right == NULL) {
            if(root->val == sum) 
                indicator = 1;
            return;
        }
        if(root->left == NULL) {
            check(root->right, sum - root->val);
            return;
        }
        if(root->right == NULL) {
            check(root->left, sum - root->val);
            return;
        }

        check(root->left, sum - root->val);
        check(root->right, sum - root->val);

    }
    bool hasPathSum(TreeNode* root, int sum) {
        check(root, sum);
        if(indicator == 1)
            return true;
        else
            return false;
    }
};
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

Path Sum