[LeetCode]112. Path Sum
题目描述
思路
递归,计算每条路径的和,当前节点为叶子节点时,比较当前和与目标和
PS: 写成目标和减去节点值的方式,可以简化代码
代码
#include <iostream>
using namespace std;
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;
path(root, root->val, sum);
return res;
}
void path(TreeNode* root, int pathSum, int sum) {
if (root->left == NULL && root->right == NULL && pathSum == sum)
res = true;
if (root->left)
path(root->left, pathSum + root->left->val, sum);
if (root->right)
path(root->right, pathSum + root->right->val, sum);
}
private:
bool res = false;
};
int main() {
TreeNode* n1 = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(4);
n1->left = n2;
//n1->right = n3;
//n2->left = n4;
Solution s;
cout << s.hasPathSum(n1, 3) << endl;
system("pause");
return 0;
}