https://leetcode.com/problems/path-sum/description/
题目大意:给定一个二叉树和一个值sum,判断是否存在一个从根节点到叶子节点的路径,使得路径上每个节点值之和等于sum?
第一种解法:递归
/**
* 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 == NULL) {
return false;
}
if (root->left == NULL && root->right == NULL) {
return sum == root->val;
}
return hasPathSum (root->left, sum - root->val)
|| hasPathSum(root->right, sum - root->val);
}
};
第二种:非递归
/**
* 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 == NULL)
{
return false;
}
stack<TreeNode*>s;
map<TreeNode*,bool>m;
s.push(root);
m[root]=true;
int cur=root->val,ok=0;
while(!s.empty())
{
TreeNode *t=s.top();
if(t->left==NULL&&t->right==NULL)
{
if(cur==sum)
return true;
}
if(t->left&&m[t->left]==false)
{
s.push(t->left);
m[t->left]=true;
cur+=t->left->val;
continue;
}
if(t->right!=NULL&&m[t->right]==false)
{
s.push(t->right);
m[t->right]=true;
cur+=t->right->val;
continue;
}
cur-=t->val;
s.pop();
}
return false;
}
};