1. 递归解法
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
if(!root->left && !root->right && root->val == sum)
return true;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
2. 迭代解法
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode *temp = st.top();
st.pop();
if (!temp->left && !temp->right) {
if (temp->val == sum) return true;
}
if (temp->right) {
temp->right->val += temp->val;
st.push(temp->right);
}
if (temp->left) {
temp->left->val += temp->val;
st.push(temp->left);
}
}
return false;
}
};