华强北 网站建设,wordpress 分类 评论,招商网站怎么做,潍坊网站建设 潍坊做网站递归
思路#xff1a; 终止条件是递归到根节点 root#xff0c;剩余 target 与根节点值相等则路径存在#xff0c;否则不存在#xff1b;递归查找左子树或者右子树存在 target target - root-val 的路径#xff1b;
/*** Definition for a binary tree node.* stru…递归
思路 终止条件是递归到根节点 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);}
};