代码随想录:路径总和
思路很简单,但是一个传参很巧妙,每次递归减去当前节点的值,就只用一个传参
/*** 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)return false;return tra(root, targetSum);}bool tra(TreeNode* node, int targetSum) {targetSum = targetSum - node->val;if (node->left == NULL && node->right == NULL) {if (targetSum == 0)return true;elsereturn false;}bool l = false, r = false;if (node->left) {l = tra(node->left, targetSum);}if (node->right) {r = tra(node->right, targetSum);}return l || r;}
};