LeetCode: Path Sum
2016-09-07 22:48
246 查看
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.
For example:
Given the below binary tree and
return true, as there exist a root-to-leaf path
/**
* Definition for a binary tree node.
* 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;
queue<struct TreeNode*> Q;
Q.push(root);
while(!Q.empty()) {
struct TreeNode* tmp = Q.front();
if (tmp->left != NULL) {
tmp->left->val += tmp->val;
Q.push(tmp->left);
}
if (tmp->right != NULL) {
tmp->right->val += tmp->val;
Q.push(tmp->right);
}
if (tmp->left == NULL && tmp->right == NULL && tmp->val == sum) return true;
Q.pop();
}
return false;
}
};
For 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->2which sum is 22.
/**
* Definition for a binary tree node.
* 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;
queue<struct TreeNode*> Q;
Q.push(root);
while(!Q.empty()) {
struct TreeNode* tmp = Q.front();
if (tmp->left != NULL) {
tmp->left->val += tmp->val;
Q.push(tmp->left);
}
if (tmp->right != NULL) {
tmp->right->val += tmp->val;
Q.push(tmp->right);
}
if (tmp->left == NULL && tmp->right == NULL && tmp->val == sum) return true;
Q.pop();
}
return false;
}
};
相关文章推荐
- [Leetcode] 64. Minimum Path Sum
- Leetcode 笔记 112 - Path Sum
- 【LeetCode】112. Path Sum
- LeetCode(124) Binary Tree Maximum Path Sum
- leetcode 之 path sum
- leetcode-Path Sum
- [leetcode] Path Sum
- LeetCode 112 Path Sum
- [LeetCode] Path Sum 求二叉树中满足要求的路径
- 开始刷题leetcode day3: Path Sum
- [leetcode] @python 112. Path Sum
- Leetcode64. Minimum Path Sum
- [leetcode] 112.Path Sum
- LeetCode-Path Sum
- LeetCode-Path Sum
- LeetCode: Path Sum
- leetcode64. Minimum Path Sum
- leetcode [Path Sum]//待整理多种解法
- 【leetcode】64. Minimum Path Sum【java】
- LeetCode 112. Path Sum