Runtime: 12 ms, faster than 76.30% of C++ online submissions for Path Sum.
Memory Usage: 19.8 MB, less than 97.92% of C++ online submissions for Path Sum.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL)
return false;
if(root->left == NULL && root->right == NULL)
return root->val == sum;
else if(root->left == NULL && root->right != NULL){
return hasPathSum(root->right, sum-root->val);
}
else if(root->left != NULL && root->right == NULL)
return hasPathSum(root->left, sum-root->val);
else{
return hasPathSum(root->right, sum-root->val) || hasPathSum(root->left, sum-root->val);
}
}
};
目前想到的也就只有深度优先搜索