112. 路径总和
思路:需要注意,要在叶子节点的时候进行判断,判断的时候不要忘记加上叶子节点的值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool flag=0;
void dfs(TreeNode* root,int sum, int targetSum){
//在叶子节点的时候进行判断
if(root->left==nullptr && root->right==nullptr){
if(sum==INT_MIN) sum=0;
//判断的时候不要忘记加上叶子节点的值。
if(sum+root->val==targetSum) flag=1;
return ;
}
if(sum==INT_MIN) sum=0;
if(root->left) dfs(root->left,sum+root->val,targetSum);
if(root->right) dfs(root->right,sum+root->val,targetSum);
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root) dfs(root,INT_MIN,targetSum);
return flag;
}
};
优化了一下,从targetSum开始减
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool flag=0;
void dfs(TreeNode* root, int targetSum){
if(root->left==nullptr && root->right==nullptr){
if(root->val==targetSum) flag=1;
return ;
}
if(root->left) dfs(root->left,targetSum-root->val);
if(root->right) dfs(root->right,targetSum-root->val);
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root) dfs(root,targetSum);
return flag;
}
};