/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(root == NULL) return false;
//suan stack
stack<pair<TreeNode*, int>> sk;
// push root
sk.push({root, root->val});
//while
while(!sk.empty())
{
auto node = sk.top();
sk.pop();
//yezi node && == sum
if(node.first->left ==NULL && node.first->right ==NULL && node.second == sum)
return true;
//zuo
if(node.first->left)
{
//尤其注意, 容易出错
sk.push({node.first->left, node.second+node.first->left->val});
}
//you
if(node.first->right)
{
//尤其注意, 容易出错
sk.push({node.first->right, node.second+node.first->right->val});
}
}
return false;
//return false;
}
};