Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Last active August 29, 2015 14:21
Show Gist options
  • Save emad-elsaid/1e417790056c85de9ebb to your computer and use it in GitHub Desktop.
Save emad-elsaid/1e417790056c85de9ebb to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stack>
using namespace std;
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
stack<TreeNode*> trail;
stack<int> sums;
trail.push(root);
sums.push(root->val);
while( !trail.empty()){
TreeNode* current = trail.top();
int current_sum = sums.top();
trail.pop();
sums.pop();
if(!(current->left || current->right) && current_sum==sum ) return true;
if(current->left){
trail.push(current->left);
sums.push(current_sum + current->left->val);
}
if(current->right){
trail.push(current->right);
sums.push(current_sum + current->right->val);
}
}
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment