Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Last active July 7, 2019 15:18
Show Gist options
  • Save yangpeng-chn/b1b38b5758ab8c6a7e08ca5d2d77fc26 to your computer and use it in GitHub Desktop.
Save yangpeng-chn/b1b38b5758ab8c6a7e08ca5d2d77fc26 to your computer and use it in GitHub Desktop.
Tree DFS
// 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