给一个目标值,判断一棵树从根到叶子是否至少有一条路径加起来的和等于目标值
比较典型的深度优先算法。
引入一个全局变量bResult, 一旦找到一条,就不再搜索其他的了。
class Solution { public: void helper(TreeNode* cur, int sum, int target, bool& bResult){ if(bResult) return; //a(cur) //lk("root",cur) //a(sum) //a(target) //dsp if(!cur->left && !cur->right){ bResult|= target-sum==cur->val; } if(cur->left) helper(cur->left, sum+cur->val, target, bResult); if(cur->right) helper(cur->right, sum+cur->val, target, bResult); } bool hasPathSum(TreeNode* root, int sum) { if(!root) return false; if(!root->left && !root->right){ return sum==root->val; } //ahd(root) bool bRet=false; //a(bRet) if(root->left) helper(root->left, root->val, sum, bRet); if(root->right) helper(root->right, root->val, sum, bRet); //dsp return bRet; } };