To a target value, it is determined whether a tree from the root to leaves combined with at least one path is equal to the target value
The typical depth-first algorithm.
The introduction of a global variable bResult, once one is found, it is no longer a search for the other.
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; } };
Running dynamic presentation http://simpledsp.com/FS/Html/lc112.html