LeetCode Path Sum IV

时间:2023-06-07 11:33:32

原题链接在这里:https://leetcode.com/problems/path-sum-iv/

题目:

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:

  1. The hundreds digit represents the depth D of this node, 1 <= D <= 4.
  2. 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.
  3. 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.

题解:

每个数字的前两位就决定了node所在的level 和 position.

那么这个node的left child 所在位置是 level + 1, 2*position-1. right child 所在位置是 level + 1, 2*position.

把所有node的位置都存起来, 当走到一个node, 它的left 和 right child 都没有记录的时候就说明走到了叶子节点, 此时记录的path sum可以累积到结果中.

Time Complexity: O(n). n是tree 的node数目.

Space: O(n).

AC Java:

 class Solution {
int sum = 0; public int pathSum(int[] nums) {
if(nums == null || nums.length == 0){
return sum;
} HashMap<Integer, Integer> hm = new HashMap<>();
for(int num : nums){
hm.put(num / 10, num % 10);
} dfs(nums[0] / 10, hm, 0);
return sum;
} private void dfs(int rootKey, Map<Integer, Integer> hm, int cur){
if(!hm.containsKey(rootKey)){
return;
} cur += hm.get(rootKey); int level = rootKey / 10;
int pos = rootKey % 10;
int leftKey = (level + 1) * 10 + 2 * pos - 1;
int rightKey = leftKey + 1; if(!hm.containsKey(leftKey) && !hm.containsKey(rightKey)){
sum += cur;
return;
} dfs(leftKey, hm, cur);
dfs(rightKey, hm, cur);
}
}

类似Path Sum III.