https://leetcode-cn.com/problems/path-sum/
递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool myPathSum(struct TreeNode *node, int tmpSum) {
// 找到叶子节点
if (!node->left && !node->right) {
if (tmpSum == 0) {
return true;
} else {
return false;
}
}
// 非叶子节点的处理:
if (node->left && myPathSum(node->left, tmpSum - node->left->val)) {
return true;
}
//右孩子
if (node->right && myPathSum(node->right, tmpSum - node->right->val)) {
return true;
}
return false;
}
bool hasPathSum(struct TreeNode* root, int targetSum){
if (!root) {
return false;
}
return myPathSum(root, targetSum - root->val);
}