forked from niveditaprity/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfspathsum.cpp
34 lines (29 loc) · 830 Bytes
/
dfspathsum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root==NULL)
{
return 0;
}
stack<pair<TreeNode*,int>>s;
s.push({root,sum-root->val});
while(!s.empty())
{
pair<TreeNode*,int>temp=s.top();
s.pop();
if(temp.first->left==NULL&&temp.first->right==NULL&&temp.second==0)
{
return true;
}
if(temp.first->left)
{
s.push({temp.first->left,temp.second-temp.first->left->val});
}
if(temp.first->right)
{
s.push({temp.first->right,temp.second-temp.first->right->val});
}
}
return false;
}
};