Path Sum IV

medium tree dfs hash map

Problem

Each entry is a 3-digit number: depth, position-in-row, value. Sum all root-to-leaf path sums.

Inputnums = [113,215,221]
Output12
Tree: 3 → (5,1). Paths: 3+5=8 and 3+1=4. Sum = 12.

def path_sum(nums):
    tree = {(n // 100, (n % 100) // 10): n % 10 for n in nums}
    def dfs(d, p, s):
        if (d, p) not in tree: return 0
        s += tree[(d, p)]
        l, r = (d + 1, 2 * p - 1), (d + 1, 2 * p)
        if l not in tree and r not in tree: return s
        return dfs(*l, s) + dfs(*r, s)
    return dfs(1, 1, 0)
function pathSum(nums) {
  const t = new Map();
  for (const n of nums) t.set((Math.floor(n / 100)) * 100 + Math.floor((n % 100) / 10), n % 10);
  const dfs = (d, p, s) => {
    const k = d * 100 + p;
    if (!t.has(k)) return 0;
    s += t.get(k);
    const lk = (d + 1) * 100 + 2 * p - 1, rk = (d + 1) * 100 + 2 * p;
    if (!t.has(lk) && !t.has(rk)) return s;
    return dfs(d + 1, 2 * p - 1, s) + dfs(d + 1, 2 * p, s);
  };
  return dfs(1, 1, 0);
}
int pathSum(int[] nums) {
    Map t = new HashMap<>();
    for (int n : nums) t.put((n / 100) * 100 + (n % 100) / 10, n % 10);
    return dfs(1, 1, 0, t);
}
int dfs(int d, int p, int s, Map t) {
    int k = d * 100 + p;
    if (!t.containsKey(k)) return 0;
    s += t.get(k);
    int lk = (d + 1) * 100 + 2 * p - 1, rk = (d + 1) * 100 + 2 * p;
    if (!t.containsKey(lk) && !t.containsKey(rk)) return s;
    return dfs(d + 1, 2 * p - 1, s, t) + dfs(d + 1, 2 * p, s, t);
}
unordered_map t;
int dfs(int d, int p, int s) {
    int k = d * 100 + p;
    if (!t.count(k)) return 0;
    s += t[k];
    int lk = (d + 1) * 100 + 2 * p - 1, rk = (d + 1) * 100 + 2 * p;
    if (!t.count(lk) && !t.count(rk)) return s;
    return dfs(d + 1, 2 * p - 1, s) + dfs(d + 1, 2 * p, s);
}
int pathSum(vector& nums) {
    for (int n : nums) t[(n / 100) * 100 + (n % 100) / 10] = n % 10;
    return dfs(1, 1, 0);
}
Time: O(n) Space: O(n)