给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
BFS
逐层向下查找,队列保存每个节点及到此节点路径长度。
/**
* 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)
return 0;
queue<pair<TreeNode*,int> > qu;
pair<TreeNode*, int> pa;
pa.first=root;
pa.second=root->val;
qu.push(pa);
while(!qu.empty())
{
TreeNode* node=qu.front().first;
int num=qu.front().second;
qu.pop();
if(!node->left&&!node->right)
{
if(num==sum)
return true;
continue;
}
if(node->left)
{
pa.first=node->left;
pa.second=num+node->left->val;
qu.push(pa);
}
if(node->right)
{
pa.first=node->right;
pa.second=num+node->right->val;
qu.push(pa);
}
}
return false;
}
};
递归
每次用sum-当前节点值传给下一节点,当根节点=sum(减去n个父节点值后)时,返回true。
/**
* 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)
return 0;
if(!root->left&&!root->right)
{
if(root->val==sum)
return true;
}
return hasPathSum(root->left,sum-root->val)||
hasPathSum(root->right,sum-root->val);
}
};