File tree 2 files changed +45
-0
lines changed
2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 44
44
102|[ Binary Tree Level Order Traversal] ( ./0102-binary-tree-level-order-traversal.js ) |Medium|
45
45
104|[ Maximum Depth of Binary Tree] ( ./0104-maximum-depth-of-binary-tree.js ) |Easy|
46
46
111|[ Minimum Depth of Binary Tree] ( ./0111-minimum-depth-of-binary-tree.js ) |Easy|
47
+ 112|[ Path Sum] ( ./0112-path-sum.js ) |Easy|
47
48
118|[ Pascal's Triangle] ( ./0118-pascals-triangle.js ) |Easy|
48
49
119|[ Pascal's Triangle II] ( ./0119-pascals-triangle-ii.js ) |Easy|
49
50
121|[ Best Time to Buy and Sell Stock] ( ./0121-best-time-to-buy-and-sell-stock.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 112. Path Sum
3
+ * https://leetcode.com/problems/path-sum/
4
+ * Difficulty: Easy
5
+ *
6
+ * Given the root of a binary tree and an integer targetSum, return true if the
7
+ * tree has a root-to-leaf path such that adding up all the values along the
8
+ * path equals targetSum.
9
+ *
10
+ * A leaf is a node with no children.
11
+ */
12
+
13
+ /**
14
+ * Definition for a binary tree node.
15
+ * function TreeNode(val, left, right) {
16
+ * this.val = (val===undefined ? 0 : val)
17
+ * this.left = (left===undefined ? null : left)
18
+ * this.right = (right===undefined ? null : right)
19
+ * }
20
+ */
21
+ /**
22
+ * @param {TreeNode } root
23
+ * @param {number } targetSum
24
+ * @return {boolean }
25
+ */
26
+ var hasPathSum = function ( root , targetSum ) {
27
+ if ( ! root ) {
28
+ return false ;
29
+ }
30
+ const result = [ ] ;
31
+
32
+ traverse ( result , root ) ;
33
+
34
+ return result . includes ( targetSum ) ;
35
+ } ;
36
+
37
+ function traverse ( result , node , sum = 0 ) {
38
+ if ( ! node . left && ! node . right ) {
39
+ result . push ( sum + node . val ) ;
40
+ }
41
+
42
+ if ( node . left ) traverse ( result , node . left , sum + node . val ) ;
43
+ if ( node . right ) traverse ( result , node . right , sum + node . val ) ;
44
+ }
You can’t perform that action at this time.
0 commit comments