方法
we can use num / 10 = 10 * depth + pos as a unique identifier for that node. The left child of such a node would have identifier 10 * (depth + 1) + 2 * pos - 1, and the right child would be one greater.
// xyv
// / \
// (x+1)(2y-1)v (x+1)(2y)v
class Solution {
int sum = 0;
// treenode_index to treenode_val
Map<Integer, Integer> map = new HashMap<>();
public int pathSum(int[] nums) {
for (int num : nums) {
int val = num % 10;
int level = num / 100, pos = num / 10 % 10;
map.put(level * 10 + pos, val);
}
int root = nums[0] / 100 * 10 + nums[0] / 10 % 10;
dfs(root, nums[0] % 10); // count in current node to sum
return sum;
}
public void dfs(int node, int curSum) {
int level = node / 10, pos = node % 10;
int left = (level + 1) * 10 + (2 * pos - 1);
int right = (level + 1) * 10 + (2 * pos);
if (!map.containsKey(left) && !map.containsKey(right)) {
sum += curSum;
return;
}
if (map.containsKey(left)) {
dfs(left, curSum + map.get(left));
}
if (map.containsKey(right)) {
dfs(right, curSum + map.get(right));
}
}
}