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
,
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.
递归求解,代码如下,需要注意的一点是,有时候代码并不在下一层终止,而是通过判断root->left是否为空的方式,直接在当前层判断是否继续向下一层运行。在树的处理中,这一点很常见。要记住。
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root == NULL)return false;
if(root->left == NULL && root->right == NULL && root->val == sum)
return true;
if(root->left && hasPathSum(root->left, sum - root->val))
return true;
if(root->right && hasPathSum(root->right, sum - root->val))
return true;
return false;
}
};