Last active
July 7, 2019 15:18
-
-
Save yangpeng-chn/b1b38b5758ab8c6a7e08ca5d2d77fc26 to your computer and use it in GitHub Desktop.
Tree DFS
This file contains 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
// Iteration | |
bool hasPathSum(TreeNode* root, int sum) { | |
if(!root) return false; | |
stack<TreeNode*>s{{root}}; | |
while(!s.empty()){ | |
TreeNode* tmp = s.top(); | |
s.pop(); | |
if(!tmp->left && !tmp->right && tmp->val == sum) | |
return true; | |
if(tmp->left){ | |
tmp->left->val += tmp->val; | |
s.push(tmp->left); | |
} | |
if(tmp->right){ | |
tmp->right->val += tmp->val; | |
s.push(tmp->right); | |
} | |
} | |
return false; | |
} | |
// Recursion | |
bool hasPathSum(TreeNode* root, int sum) { | |
if(!root) | |
return false; | |
if(!root->left && !root->right && root->val == sum) | |
return true; | |
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment