# [LeetCode] 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 题目讲解汇总(持续更新中...)

posted @ 2014-10-20 13:08  Grandyang  阅读(17117)  评论(4编辑  收藏  举报