666. Path Sum IV
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to calculate the sum of all root-to-leaf path sums in a binary tree. The tree is represented in a peculiar way: an array of three-digit integers. Each integer encodes a node's depth, its position within that level, and its value. The core of the problem is to first understand this encoding to reconstruct the tree's structure and then traverse it to compute the path sums.
Solution
Path Sum IV in Python
class Solution:
def pathSum(self, nums: List[int]) -> int:
# Create a map from a node's position key to its value.
# Key: 10 * depth + position
tree = {num // 10: num % 10 for num in nums}
self.total_sum = 0
def dfs(node_key, current_path_sum):
# The value of the current node is added to the path sum.
current_path_sum += tree[node_key]
# Decode depth and position from the key.
depth = node_key // 10
pos = node_key % 10
# Calculate potential children's keys.
left_child_key = (depth + 1) * 10 + (2 * pos - 1)
right_child_key = (depth + 1) * 10 + (2 * pos)
is_leaf = True
# Recurse for existing children.
if left_child_key in tree:
is_leaf = False
dfs(left_child_key, current_path_sum)
if right_child_key in tree:
is_leaf = False
dfs(right_child_key, current_path_sum)
# If it's a leaf, add the path sum to the total.
if is_leaf:
self.total_sum += current_path_sum
# Start DFS from the root (depth=1, pos=1, key=11)
if 11 in tree:
dfs(11, 0)
return self.total_sum
Path Sum IV in Java
class Solution {
private int totalSum = 0;
private Map<Integer, Integer> tree = new HashMap<>();
public int pathSum(int[] nums) {
// Build a map to represent the tree
// Key: 10 * depth + position
// Value: node's value
for (int num : nums) {
int key = num / 10; // Combines depth and position
int value = num % 10;
tree.put(key, value);
}
// Start DFS from the root (depth=1, pos=1)
dfs(11, 0);
return totalSum;
}
private void dfs(int nodeKey, int currentPathSum) {
// Get depth, position, and value of the current node
int depth = nodeKey / 10;
int pos = nodeKey % 10;
int value = tree.get(nodeKey);
currentPathSum += value;
// Calculate potential children's keys
int leftChildKey = (depth + 1) * 10 + (2 * pos - 1);
int rightChildKey = (depth + 1) * 10 + (2 * pos);
boolean isLeaf = true;
// Check if left child exists and recurse
if (tree.containsKey(leftChildKey)) {
isLeaf = false;
dfs(leftChildKey, currentPathSum);
}
// Check if right child exists and recurse
if (tree.containsKey(rightChildKey)) {
isLeaf = false;
dfs(rightChildKey, currentPathSum);
}
// If it's a leaf node, add the complete path sum to the total
if (isLeaf) {
totalSum += currentPathSum;
}
}
}
Path Sum IV in C++
class Solution {
public:
int pathSum(vector<int>& nums) {
// Use a map to store the tree structure.
// Key: 10 * depth + position
// Value: node's value
unordered_map<int, int> tree;
for (int num : nums) {
int key = num / 10; // Extract depth and position part
int value = num % 10; // Extract value part
tree[key] = value;
}
int totalSum = 0;
// Start DFS from the root (depth=1, pos=1)
dfs(11, 0, tree, totalSum);
return totalSum;
}
private:
void dfs(int nodeKey, int currentPathSum, unordered_map<int, int>& tree, int& totalSum) {
// Get depth, position, and value of the current node
int depth = nodeKey / 10;
int pos = nodeKey % 10;
int value = tree[nodeKey];
currentPathSum += value;
// Calculate potential children's keys
int leftChildKey = (depth + 1) * 10 + (2 * pos - 1);
int rightChildKey = (depth + 1) * 10 + (2 * pos);
bool isLeaf = true;
// Check if left child exists
if (tree.count(leftChildKey)) {
isLeaf = false;
dfs(leftChildKey, currentPathSum, tree, totalSum);
}
// Check if right child exists
if (tree.count(rightChildKey)) {
isLeaf = false;
dfs(rightChildKey, currentPathSum, tree, totalSum);
}
// If it's a leaf node, add the path sum to the total
if (isLeaf) {
totalSum += currentPathSum;
}
}
};
Path Sum IV in TypeScript
function pathSum(nums: number[]): number {
// Use a Map to store the tree structure.
// Key: 10 * depth + position
// Value: node's value
const tree = new Map<number, number>();
for (const num of nums) {
const key = Math.floor(num / 10); // Extract depth and position part
const value = num % 10; // Extract value part
tree.set(key, value);
}
let totalSum = 0;
function dfs(nodeKey: number, currentPathSum: number): void {
// Get depth, position, and value of the current node
const depth = Math.floor(nodeKey / 10);
const pos = nodeKey % 10;
const value = tree.get(nodeKey)!;
currentPathSum += value;
// Calculate potential children's keys
const leftChildKey = (depth + 1) * 10 + (2 * pos - 1);
const rightChildKey = (depth + 1) * 10 + (2 * pos);
let isLeaf = true;
// Check if left child exists and recurse
if (tree.has(leftChildKey)) {
isLeaf = false;
dfs(leftChildKey, currentPathSum);
}
// Check if right child exists and recurse
if (tree.has(rightChildKey)) {
isLeaf = false;
dfs(rightChildKey, currentPathSum);
}
// If it's a leaf node, add the complete path sum to the total
if (isLeaf) {
totalSum += currentPathSum;
}
}
// Start DFS from the root (depth=1, pos=1), which must exist.
if (tree.has(11)) {
dfs(11, 0);
}
return totalSum;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.