方法一:迭代,BFS。为每个节点保存一个从root到当前节点的sum和,若到了叶子节点,比对该sum和与给定的sum是否相等。
/**
* Definition for binary tree
* 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;
stack<pair<TreeNode*,int>> s;
s.push(make_pair(root,root->val));
while(!s.empty()) {
auto node = s.top().first;
auto tree_sum = s.top().second;
s.pop();
if(node->left == NULL && node->right == NULL && tree_sum == sum) {
return true;
}
if(node->left != NULL) {
s.push(make_pair(node->left, tree_sum + node->left->val));
}
if(node->right != NULL) {
s.push(make_pair(node->right, tree_sum + node->right->val));
}
}
return false;
}
};
方法二:递归
/**
* Definition for binary tree
* 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 == NULL && root->right == NULL) {
return root->val == sum;
}
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};