题意:给定一个二叉树和一个整数sum,问从根节点到叶子节点的所有路径中,是否有等于sum的。
解:明显用递归来做,只要左右子树有一个返回true,那么总结果就是true。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root==NULL){
return false;
}
if(!root->left&&!root->right&&sum==root->val){
return true;
}
return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}
};