# 112. 路径总和

var hasPathSum = function(root, targetSum) {
  if (!root) return false
  let is = false

  dfs(root, 0)

  function dfs(node, num) {
    if (!node.left && !node.right) {
      if (is) return
      if (num + node.val === targetSum) is = true
      return
    }

    node.left && dfs(node.left, num + node.val)
    node.right && dfs(node.right, num + node.val)
  }

  return is
}
console.log(
  hasPathSum(
    {
      val: 5,
      left: {
        val: 4,
        left: {
          val: 11,
          left: {
            val: 7,
          },
          right: {
            val: 2,
          },
        },
      },
      right: {
        val: 8,
        left: {
          val: 13,
        },
        right: {
          val: 4,
          right: {
            val: 1,
          },
        },
      },
    },
    22
  )
)

console.log(
  hasPathSum(
    {
      val: 1,
      left: {
        val: 2,
      },
    },
    1
  )
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Last Updated: 6/27/2023, 7:40:45 PM