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);
}
};