标签:
思路:用广度优先搜索,将当前节点的值传到下一层节点即可。即将每一个节点的值更新为从根节点到该点的值的和
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (!root)
return false;
queue<TreeNode*> qNode;
qNode.push(root);
TreeNode* tmpNode = NULL;
while (!qNode.empty())
{
int qSize = qNode.size();
for (size_t i = 0; i < qSize; i++)
{
tmpNode = qNode.front();
if (tmpNode->val == sum && !tmpNode->left && !tmpNode->right)
{
return true;
}
else
{
if (tmpNode->left)
{
tmpNode->left->val += tmpNode->val;
qNode.push(tmpNode->left);
}
if (tmpNode->right)
{
tmpNode->right->val += tmpNode->val;
qNode.push(tmpNode->right);
}
}
qNode.pop();
}
}
return false;
}
};
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/d3efa7b9fe192e34fd8068884e95cbdb.html