@@ -57,18 +57,71 @@ Given the following tree and <code>sum = 22,</code></p>
57
57
58
58
59
59
## Solutions
60
-
60
+ Depth-First-Search
61
61
62
62
### Python3
63
+ Using the idea of recursion, at each recursion to a node.
64
+ - If root.val-sum == 0, add 1 to the result
65
+ - Consider two scenarios for inclusion or exclusion of this node from the pathway
63
66
64
- ``` python
67
+ Special case: if the parent node of this node is in the path, this node must be included in the path (the path cannot be broken)
65
68
69
+ ``` python
70
+ class Solution :
71
+ def pathSum (self , root : TreeNode, sum : int ) -> int :
72
+ def dfs (root , sum , flag ):
73
+ nonlocal ans
74
+ if not root:
75
+ return 0
76
+ if sum - root.val == 0 :
77
+ ans += 1
78
+ if flag == 0 :
79
+ dfs(root.left, sum , 0 )
80
+ dfs(root.right, sum , 0 )
81
+ dfs(root.left, sum - root.val, 1 )
82
+ dfs(root.right, sum - root.val, 1 )
83
+
84
+ if not root:
85
+ return 0
86
+ ans = 0
87
+ dfs(root, sum , 0 )
88
+ return ans
66
89
```
67
90
68
91
### Java
92
+ Use to 2 recursive processes.
69
93
70
- ``` java
94
+ - BFS: (traverse) traverses each tree node.
95
+ - DFS: Starting from each tree node, the nodes sum to see if sum can be satisfied.
96
+
97
+ Note that node values can be positive or negative, and all possible paths need to be exhausted.
71
98
99
+ ``` java
100
+ class Solution {
101
+ int ans = 0 ;
102
+ public int pathSum (TreeNode root , int sum ) {
103
+ traverse(root, sum);
104
+ return ans;
105
+ }
106
+
107
+ void traverse (TreeNode root , int sum ) {
108
+ if (root == null ) return ;
109
+ ans += dfs(root, sum, 0 );
110
+ traverse(root. left, sum);
111
+ traverse(root. right, sum);
112
+ }
113
+
114
+ // check if sum of path is sum.
115
+ int dfs (TreeNode root , int sum , int cur ) {
116
+ if (root == null ) return 0 ;
117
+ cur += root. val;
118
+ int res = 0 ;
119
+ if (cur == sum) res++ ;
120
+ res += dfs(root. left, sum, cur);
121
+ res += dfs(root. right, sum, cur);
122
+ return res;
123
+ }
124
+ }
72
125
```
73
126
74
127
### ...
0 commit comments