力扣112. 路径总和

递归

  • 思路:
    • 终止条件是递归到根节点 root,剩余 target 与根节点值相等则路径存在,否则不存在;
    • 递归查找左子树或者右子树存在 target = target - root->val 的路径;
/**
 * 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;
        }

        if ((root->left == nullptr) && (root->right == nullptr)) {
            return (targetSum == root->val);
        }

        return hasPathSum(root->left, targetSum - root->val) ||
               hasPathSum(root->right, targetSum - root->val);
    }
};

你可能感兴趣的:(力扣实践,leetcode,算法,职场和发展)