# 112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and `sum = 22`,

``````      5
/ \
4   8
/   / \
11  13  4
/  \      \
7    2      1
``````

return true, as there exist a root-to-leaf path `5->4->11->2` which sum is 22.

``````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);
}
};
``````

``````class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
stack<TreeNode*> st{{root}};
while (!st.empty()) {
TreeNode *t = st.top(); st.pop();
if (!t->left && !t->right) {
if (t->val == sum) return true;
}
if (t->right) {
t->right->val += t->val;
st.push(t->right);
}
if (t->left) {
t->left->val += t->val;
st.push(t->left);
}
}
return false;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/112

Binary Tree Maximum Path Sum

Path Sum II

Sum Root to Leaf Numbers

Binary Tree Preorder Traversal

https://leetcode.com/problems/path-sum/

https://leetcode.com/problems/path-sum/discuss/36534/My-java-no-recursive-method

https://leetcode.com/problems/path-sum/discuss/36378/AcceptedMy-recursive-solution-in-Java

https://leetcode.com/problems/path-sum/discuss/36382/Accepted-By-using-postorder-traversal

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation