If the depth of a tree is smaller than 5
, then this tree can be represented by a list of three-digits integers.
For each integer in this list:
- The hundreds digit represents the depth
D
of this node,1 <= D <= 4.
- The tens digit represents the position
P
of this node in the level it belongs to,1 <= P <= 8
. The position is the same as that in a full binary tree. - The units digit represents the value
V
of this node,0 <= V <= 9.
Given a list of ascending
three-digits integers representing a binary with the depth smaller than 5. You need to return the sum of all paths from the root towards the leaves.
Example 1:
Input: [113, 215, 221] Output: 12 Explanation: The tree that the list represents is: 3 / \ 5 1 The path sum is (3 + 5) + (3 + 1) = 12.
Example 2:
Input: [113, 221] Output: 4 Explanation: The tree that the list represents is: 3 \ 1 The path sum is (3 + 1) = 4.
思路:用数组表示tree就好了,记得之前求pathSum,有个方法是从上往下累加,累加到子节点,这里也是类似的思路
当然也可以用Map来代表数
import java.util.Arrays;
class Solution {
public int pathSum(int[] nums) {
if(nums.length == 1) return nums[0]%10;
int[] a = new int[100];
Arrays.fill(a, -1);
for(int i : nums) a[i/10] = i%10;
int ret = 0;
for(int i=2; i<=4; i++) {
for(int j=1; j<=8; j++) {
int idx = i*10 + j, pre = (i-1)*10+(j+1)/2,
next1 = (i+1)*10+2*j, next2 = (i+1)*10+2*j-1;
if(a[idx] != -1 && a[pre] != -1)
a[idx] += a[pre];
if(a[next1] == -1 && a[next2] == -1 && a[idx]!=-1)
ret += a[idx];
}
}
return ret;
}
}