Last active
August 29, 2015 14:21
-
-
Save emad-elsaid/1e417790056c85de9ebb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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