题目:
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.
解答:
简单的DFS
/**
* 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 DFS(TreeNode* root, int cur)
{
if(root->left == NULL && root->right == NULL)
{
if(cur + root->val == tag)
return true;
else
return false;
}
if(root->left == NULL)
return DFS(root->right, cur + root->val);
else if(root->right == NULL)
return DFS(root->left, cur + root->val);
else
return DFS(root->left,cur + root->val) || DFS(root->right, cur + root->val);
}
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL)
return false;
tag = sum;
return DFS(root,0);
}
private:
int tag;
};