题目:
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.
思路:
为了便于查找方便,我们首先将每个节点映射到一个哈希表中,其中key是节点的位置,value是节点的值。由于符合满二叉树的性质,所以我们很容易根据一个父结点的key找到它的两个左右子孩子所对应的节点。这样这个问题就和其它的path sum问题没有区别了。
class Solution {
public:
int pathSum(vector<int>& nums) {
unordered_map<int, int> hash;
for (auto num : nums) {
int hundreds = num / 100;
int tens = (num % 100) / 10;
int units = num % 10;
hash[num - units] = units;
}
int hundreds = nums[0] / 100;
int tens = (nums[0] % 100) / 10;
int total_sum = 0;
pathSum(hundreds, tens, 0, total_sum, hash);
return total_sum;
}
private:
void pathSum(int hundreds, int tens, int sum, int &total_sum,
unordered_map<int, int> &hash) {
sum += hash[hundreds * 100 + tens * 10];
int left = hash.count((hundreds + 1) * 100 + (2 * tens - 1) * 10);
int right = hash.count((hundreds + 1) * 100 + (2 * tens) * 10);
if (left == 0 && right == 0) { // this node is a leaf
total_sum += sum;
return;
}
if (left != 0) {
pathSum(hundreds + 1, 2 * tens - 1, sum, total_sum, hash);
}
if (right != 0) {
pathSum(hundreds + 1, 2 * tens, sum, total_sum, hash);
}
}
};