Clean Java Solution with one HashMap


  • 0
    L
    public int pathSum(int[] nums) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            Map<Integer, Integer> map = new HashMap<>();
            for (int n : nums) {
                int val = n % 10, level = n / 100 % 10, pos = n / 10 % 10;
                int idx = (int) (Math.pow(2, level - 1) - 1 + pos);
                int root = idx / 2;
                map.put(idx, val + map.getOrDefault(root, 0));
            }
            int res = 0;
            for (int idx : map.keySet()) {
                if (!map.containsKey(2 * idx) && !map.containsKey(2 * idx + 1)) {
                    res += map.get(idx);
                }
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.