LeetCode-112. Path Sum

网友投稿 254 2022-08-29

LeetCode-112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and ​​sum = 22​​,

5 / \ 4 8 / / \ 11 13 4 / \ \7 2 1

return true, as there exist a root-to-leaf path ​​5->4->11->2​​ which sum is 22.

题解:

class Solution {public: bool hasPathSum(TreeNode* root, int sum) { if (root == NULL) { return false; } if (root->left == NULL && root->right == NULL) { if (root->val == sum) { return true; } else { return false; } } return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:快手发布《奢侈品行业数据价值报告》,全面解构奢侈品营销生态!
下一篇:LeetCode-771. Jewels and Stones
相关文章

 发表评论

暂时没有评论,来抢沙发吧~