一、题目内容

image.png

二、题解

解法1:

思路

代码

  1. public class Solution {
  2. boolean has = false;
  3. public boolean hasPathSum (TreeNode root, int sum) {
  4. // write code here
  5. recur(root, sum);
  6. return has;
  7. }
  8. private void recur(TreeNode root, int sum){
  9. if (root == null) {
  10. return;
  11. }
  12. sum -= root.val;
  13. if(sum == 0 && root.left == null && root.right == null){
  14. has = true;
  15. return;
  16. }
  17. recur(root.left, sum);
  18. recur(root.right, sum);
  19. }
  20. }