欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【树】【回溯】leetcode_112_路径总和

程序员文章站 2022-03-03 11:02:23
...

【树】【回溯】leetcode_112_路径总和

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr) return false;
        return traversal(root, targetSum-root->val);
    }

    bool traversal (TreeNode* cur, int count){
        if (cur->left == nullptr && cur ->right == nullptr && count==0) return true;
        if (cur->left == nullptr && cur ->right == nullptr && count!=0) return false;

        if (cur->left != nullptr){
            count = count - cur->left->val;
            bool re = traversal(cur->left, count);
            if (re) return true;
            count += cur->left->val;
        }

        if (cur->right != nullptr){
            count = count - cur->right->val;
            bool re = traversal(cur->right, count);
            if (re) return true;
            count += cur->right->val;
        }
        return false;


    }
};
相关标签: 刷题的日常