递归实现即可
class Solution { public: bool hasPathSum(TreeNode *root, int sum) { if(!root) return false; if(root->left ==nullptr&&root->right==nullptr&&root->val==sum) return true; return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val); } };
时间: 2024-12-17 08:30:14