原题链接在这里:https://leetcode.com/problems/path-sum-iv/description/
题目:
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:
- The hundreds digit represents the depth
D
of this node,1 <= D <= 4.
- 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. - 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 res; 3 HashMap<Integer, Integer> hm; 4 public int pathSum(int[] nums) { 5 res = 0; 6 hm = new HashMap<Integer, Integer>(); 7 for(int num : nums){ 8 hm.put(num/10, num%10); 9 } 10 11 dfs(nums[0]/10, 0); 12 return res; 13 } 14 15 private void dfs(int node, int preSum){ 16 if(!hm.containsKey(node)){ 17 return; 18 } 19 20 preSum += hm.get(node); 21 22 int level = node/10; 23 int pos = node%10; 24 int left = (level+1)*10 + 2*pos - 1; 25 int right = left + 1; 26 if(!hm.containsKey(left) && !hm.containsKey(right)){ 27 res += preSum; 28 }else{ 29 dfs(left, preSum); 30 dfs(right, preSum); 31 } 32 } 33 }