原题
https://leetcode.com/problems/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.
For example:
Given the below binary tree and sum = 22,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
翻译:给一棵二叉树和一个数值,判断是否有一条从树根到叶节点的路径,使得该路径上的节点的值的和为这个给定值。
如图中,给定22,有 5->4->11->2是符合要求的。
思路
树的问题,很多用递归的方法解决比较简单,这边就用递归的思想——对于每个节点,无非就是用目标值减去节点本身的值,然后继续寻求一条这样的路径(减去自己的值,就是不包括自己的到叶节点的路径了)。
代码
问题比较简单,代码应该还是能解释他自己。
/**
* 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;
return hasSum(root,sum,0);
}
bool hasSum(TreeNode* theRoot, int sum, int tempSum)
{
if(theRoot->left == NULL && theRoot->right == NULL) return theRoot->val + tempSum == sum;
if(theRoot->left != NULL)
{
if(theRoot->right != NULL)
return hasSum(theRoot->left,sum,tempSum + theRoot->val) || hasSum(theRoot->right,sum,tempSum + theRoot->val);
else
return hasSum(theRoot->left,sum,tempSum + theRoot->val);
}
else
return hasSum(theRoot->right,sum,tempSum + theRoot->val);
}
};