Path Sum IV
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. 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. Input:
[113, 221]
Output:
4
Explanation:
The tree that the list represents is:
3
\
1
The path sum is (3 + 1) = 4. // 用数组表示二叉树,类似于heap的表示法,然后就和普通的求path sum 没有区别了
class Solution {
int pathSum;
public int pathSum(int[] nums) {
if (nums == null || nums.length == 0) return 0;
Integer[] tree = new Integer[32];
Arrays.fill(tree, null);
// 构建树
for (int num : nums) {
int index = (int)Math.pow(2, num / 100 - 1) + (num / 10) % 10 - 1;
tree[index] = num % 10;
}
// 计算path sum
pathSum = 0;
helper(tree, 1, 0);
return pathSum;
}
private void helper(Integer[] tree, int root, int path) {
if (tree[root] == null) return;
if (tree[getLeft(root)] == null && tree[getRight(root)] == null) {
pathSum += path + tree[root];
return;
}
helper(tree, getLeft(root), path + tree[root]);
helper(tree, getRight(root), path + tree[root]);
}
private int getLeft(int i) {
return 2 * i;
}
private int getRight(int i) {
return 2 * i + 1;
}
} // 使用 hashmap 存放每个node,key 即为每个node用heap形式表示时候的index,这样和之前类似,可以直接检查
// 一个node的左右孩子是否存在
class Solution {
int pathSum;
public int pathSum(int[] nums) {
if (nums == null || nums.length == 0) return 0;
// 先将每个节点和其index存入map
Map<Integer, Integer> tree = new HashMap<>();
for (int num : nums) {
tree.put(getIndex(num), num % 10);
}
// 然后从root(1)出发,求和
helper(tree, 1, 0);
return pathSum;
}
private void helper(Map<Integer, Integer> tree, int root, int path) {
if (! tree.containsKey(root)) return;
if (! tree.containsKey(getLeft(root)) && ! tree.containsKey(getRight(root))) {
pathSum += path + tree.get(root);
}
helper(tree, getLeft(root), path + tree.get(root));
helper(tree, getRight(root), path + tree.get(root));
}
private int getIndex(int input) {
return (int)Math.pow(2, input / 100 - 1) + input / 10 % 10 - 1;
}
private int getLeft(int i) {
return 2 * i;
}
private int getRight(int i) {
return 2 * i + 1;
}
} class Solution:
def pathSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def helper(root, path):
if not root in tree: return
path += tree[root]
if not root * 2 in tree and not root * 2 + 1 in tree:
self.ret += path
else:
helper(root * 2, path)
helper(root * 2 + 1, path)
self.ret = 0
tree = {}
for node in nums:
tree[2 ** (node // 100 - 1) + node % 100 // 10 - 1] = node % 10
helper(1, 0)
return self.ret