LC.112. 路径总和
思路:递归水题,直接遍历到每个叶子结点时特判一下是否等于即可。
时间复杂度:
/**
* 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:
int f,S;
void dfs(TreeNode *u,int s){
if(u->left==nullptr&&u->right==nullptr) {
if(S==s) f=1;
return ;
}
if(u->left!=nullptr) dfs(u->left,s+u->left->val);
if(u->right!=nullptr) dfs(u->right,s+u->right->val);
}
bool hasPathSum(TreeNode* root, int sum) {
f=0,S=sum;
if(root==nullptr) return 0;
dfs(root,root->val);
return f;
}
};
也可以直接在函数里面递归,不过官方解法貌似没有剪枝,很慢。
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root==nullptr) return 0;
if(root->left == nullptr && root->right == nullptr)
return sum==root->val;
return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}
};