leetcode: Path Sum
2013-05-30 13:47
435 查看
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
sum is 22.
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 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!root) return false; if (root->left==NULL && root->right==NULL) { if (root->val == sum) { return true; } } bool bFound = false; bFound = hasPathSum(root->left, sum-(root->val)); if (bFound) return true; bFound = hasPathSum(root->right, sum-(root->val)); return bFound; } };
相关文章推荐
- 算法作业HW11:Leetcode90 Path Sum
- 【LeetCode】64. Minimum Path Sum
- [面试真题] LeetCode:Path Sum
- LeetCode--Path Sum
- LeetCode 64. Minimum Path Sum(最小和的路径)
- LeetCode(35)-Path Sum
- Path Sum - LeetCode
- Leetcode 112 Path Sum
- LeetCode Path Sum
- 【leetcode刷题笔记】Path Sum
- LeetCode 112. Path Sum
- LeetCode 112. Path Sum
- LeetCode 64. Minimum Path Sum
- [leetcode] 112. Path Sum
- Leetcode:Path Sum
- LeetCode 112 Path Sum
- leetcode - 112. Path Sum
- DP问题—Leetcode 64. Minimum Path Sum
- LeetCode_Path Sum
- LeetCode: 112. Path Sum