解法1:分治。
注意这题一定要是从root到leaf,没有到leaf就算出来sum的不算solution。
#include <iostream>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
if ((root->val==sum) && !root->left && !root->right) return true;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
int main()
{
TreeNode a(5);
TreeNode b(4);
TreeNode c(8);
TreeNode d(11);
TreeNode e(13);
TreeNode f(4);
TreeNode g(7);
TreeNode h(2);
TreeNode i(1);
a.left=&b;
a.right=&c;
b.left=&d;
c.left=&e;
c.right=&f;
d.left=&g;
d.right=&h;
f.right=&i;
cout<<hasPathSum(&a, 22)<<endl;
TreeNode j(1);
TreeNode k(2);
j.left=&k;
cout<<hasPathSum(&j, 1)<<endl;
return 0;
}
解法2: 遍历。
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
helper(root, targetSum);
return found;
}
private:
bool found = false;
void helper(TreeNode *root, int targetSum) {
if (found || !root) return;
if (!root->left && !root->right && root->val == targetSum) {
found = true;
}
helper(root->left, targetSum - root->val);
helper(root->right, targetSum - root->val);
}
};
解法3:另一种遍历。在前序遍历和后序遍历的位置加代码,也就是回溯算法!
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
target = targetSum;
helper(root);
return found;
}
private:
bool found = false;
int sum = 0, target = 0;
void helper(TreeNode *root) {
if (found || !root) return;
sum += root->val;
if (!root->left && !root->right && sum == target) {
found = true;
}
helper(root->left);
helper(root->right);
sum -= root->val;
}
};