题意:判断是否存在从根结点到叶结点,路上结点之和为所给的值的路径。
思路:DFS。
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL) return false;
sum -= root->val;
bool leftmark = false;
bool rightmark = false;
if(root->left == NULL && root->right == NULL && sum == 0) return true;
if(root->left) {
//if(sum == 0) leftmark =false;
leftmark = hasPathSum(root->left, sum);
}
if(root->right) {
//if(sum == 0) rightmark = false;
rightmark = hasPathSum(root->right, sum);
}
if(leftmark || rightmark) return true;
else return false;
}
};