路径和:不能将叶节点向下扩展一层nullptr来标记这个节点是叶节点
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 Sum(TreeNode* root,int num,int target)
{
// 叶节点,不能使用叶节点之后的节点进行判断
// 1 2 这种情况
// 如果向根节点的右树发展就是对的,可是这就与题目相悖
num+=root->val;
if(num==target && !root->left && !root->right) return true;
if((!root->left && !root->right) && num != target) return false;
if(root->left && Sum(root->left,num,target)) return true;
if(root->right && Sum(root->right,num,target)) return true;
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==nullptr) return false;
return Sum(root,0,targetSum);
}
};
优秀代码
class Solution {
public:
bool Sum(TreeNode* root,int num,int target)
{
if(root==nullptr) return false;
num+=root->val;
if(!root->left && !root->right)
{
if(num== target) return true;
return false;
}
return Sum(root->left,num,target) || Sum(root->right,num,target);
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==nullptr) return false;
return Sum(root,0,targetSum);
}
};