题目:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
/***********************法一:: 递归法**********************/
// // 这里写的比较繁杂
/*
这里关于回溯写一下自己的想法:因为传入的参数 有节点 和一个int 类型变量,因此
在处理递归逻辑的时候,需要对节点进行处理,因为要进入下一层,而处理完,还
需要回溯到本层,这样才能保证本函数的节点和本函数的值的正确的对应关系,
回溯就相当于撤销了递归处理节点的过程而已。
通常可以分开来写,或者直接写,
*/
// bool hasPathSum(TreeNode* root, int targetSum) {
// if(root == nullptr)
// {
// return false;
// }
// if(root->left == nullptr && root->right == nullptr&&targetSum-root->val == 0)
// {
// return true;
// }
// if(root->left == nullptr && root->right == nullptr)
// {
// return false;
// }
// // 单层递归逻辑
// if(root->left != nullptr)
// {
// if(hasPathSum(root->left,targetSum-root->val))
// {
// return true;
// }
// }
// if(root->right != nullptr)
// {
// if(hasPathSum(root->right,targetSum-root->val))
// {
// return true;
// }
// }
// return false;
// }
// /*****************简化些的递归************************/
// bool hasPathSum(TreeNode* root, int targetSum)
// {
// if(root == nullptr)
// {
// return false;
// }
// if(root->left == nullptr && root->right == nullptr && targetSum-root->val == 0)
// {
// return true;
// }
// return hasPathSum(root->left,sum-root->val) ||
// hasPathSum(root->right,sum-root->val)
// }
/********************法二::迭代法******************************/
bool hasPathSum(TreeNode* root, int targetSum)
{
if(root== nullptr)
{
return false;
}
// 定义一个不一样的栈
stack<pair<TreeNode*,int>> st;
st.push(pair<TreeNode*,int>(root,root->val));
while(!st.empty())
{
pair<TreeNode*,int> node = st.top();
st.pop();
// 如果该节点是叶子节点,同时该节点的路径数值等于 sum,那么就返回 true
if(node.first->left == nullptr && node.first->right == nullptr && node.second == targetSum)
{
return true;
}
// 右节点 以及对应的 数值路径 作为一个对组 压栈
if(node.first->right != nullptr)
{
st.push(pair<TreeNode*,int>(node.first->right,
node.second+node.first->right->val));
}
// 同理,左节点 以及对应的 数值路径 作为一个对组 压栈
if(node.first->left != nullptr)
{
st.push(pair<TreeNode*,int>(node.first->left,
node.second+node.first->left->val));
}
}
return false;
}
};