这个题虽然是个简单题,但是也不是不需要动脑筋。
简单的dfs还是要会的。稍微注意的是那个返回值,使用值引用会更好。然后找到路径就提前退出。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
bool res = false;
dfs(root, 0, sum, res);
return res;
}
void dfs(TreeNode* root, int cur, int sum,bool &res) {
// write code here
if(root == NULL || res){
return;
}
if(root->left != NULL){
dfs(root->left,cur + root->val,sum, res);
}
if(root->right != NULL){
dfs(root->right,cur + root->val,sum, res);
}
if(root->left == NULL && root->right == NULL){
if(cur + root->val == sum){
res = true;
}else{
res = false;
}
}
}
};



京公网安备 11010502036488号