LeetCode 666. Path Sum IV

原题链接在这里: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:

 1 class Solution {
 2     int sum = 0;
 3     
 4     public int pathSum(int[] nums) {
 5         if(nums == null || nums.length == 0){
 6             return sum;
 7         }
 8         
 9         HashMap<Integer, Integer> hm = new HashMap<>();
10         for(int num : nums){
11             hm.put(num / 10, num % 10);
12         }
13         
14         dfs(nums[0] / 10, hm, 0);
15         return sum;
16     }
17     
18     private void dfs(int rootKey, Map<Integer, Integer> hm, int cur){
19         if(!hm.containsKey(rootKey)){
20             return;
21         }
22         
23         cur += hm.get(rootKey);
24         
25         int level = rootKey / 10;
26         int pos = rootKey % 10;
27         int leftKey = (level + 1) * 10 + 2 * pos - 1;
28         int rightKey = leftKey + 1;
29         
30         if(!hm.containsKey(leftKey) && !hm.containsKey(rightKey)){
31             sum += cur;
32             return;
33         }
34         
35         dfs(leftKey, hm, cur);
36         dfs(rightKey, hm, cur);
37     }
38 }

类似Path Sum III.

posted @ 2017-12-24 16:28  Dylan_Java_NYC  阅读(483)  评论(0编辑  收藏  举报