22
33import com .fishercoder .common .classes .TreeNode ;
44
5+ import java .util .HashMap ;
6+ import java .util .Map ;
7+
58/**
69 * 666. Path Sum IV
710 * If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers.
1619 The units digit represents the value V of this node, 0 <= V <= 9.
1720
1821 Given a list of ascending three-digits integers representing a binary with the depth smaller than 5.
19- You need to return the sum of all paths from the root towards the leaves.
22+ You need to return the totalSum of all paths from the root towards the leaves.
2023
2124 Example 1:
2225
2831 / \
2932 5 1
3033
31- The path sum is (3 + 5) + (3 + 1) = 12.
34+ The path totalSum is (3 + 5) + (3 + 1) = 12.
3235
3336 Example 2:
3437
@@ -40,7 +43,7 @@ The path sum is (3 + 5) + (3 + 1) = 12.
4043 \
4144 1
4245
43- The path sum is (3 + 1) = 4.
46+ The path totalSum is (3 + 1) = 4.
4447
4548 */
4649public class _666 {
@@ -125,4 +128,38 @@ private TreeNode constructTree(int[] nums) {
125128 return root ;
126129 }
127130 }
131+
132+ public static class Solution2 {
133+ public int totalSum = 0 ;
134+
135+ public int pathSum (int [] nums ) {
136+ Map <Integer , Integer > map = new HashMap <>();
137+ for (int i = 0 ; i < nums .length ; i ++) {
138+ int key = nums [i ] / 10 ;
139+ int value = nums [i ] % 10 ;
140+ map .put (key , value );
141+ }
142+ dfs (nums [0 ] / 10 , 0 , map );
143+ return totalSum ;
144+ }
145+
146+ private void dfs (int node , int preSum , Map <Integer , Integer > map ) {
147+ int level = node / 10 ;
148+ int pos = node % 10 ;
149+ int leftChild = (level + 1 ) * 10 + pos * 2 - 1 ;
150+ int rightChild = (level + 1 ) * 10 + pos * 2 ;
151+ int currSum = preSum + map .get (node );
152+ if (!map .containsKey (leftChild ) && !map .containsKey (rightChild )) {
153+ totalSum += currSum ;
154+ return ;
155+ }
156+
157+ if (map .containsKey (leftChild )) {
158+ dfs (leftChild , currSum , map );
159+ }
160+ if (map .containsKey (rightChild )) {
161+ dfs (rightChild , currSum , map );
162+ }
163+ }
164+ }
128165}
0 commit comments