LeetCode 666: Path Sum IV Solution

Master LeetCode problem 666 (Path Sum IV), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

The problem asks us to find the sum of all paths from the root node to the leaf nodes in a binary tree. Each node has a unique value from 1 to 15. The path should be formed by connecting parent nodes to child nodes and concatenating their values. The unique path is defined as the sequence of nodes from the root to the leaf node. We need to find the sum of all unique paths.

To solve this problem, we can perform a depth-first search (DFS) traversal of the binary tree. We will keep track of the current path sum and the current path in each recursive call. Whenever we reach a leaf node, we add the current path sum to the total sum. :

Solution Code

class Solution {
    int totalSum = 0;
    
    public int pathSum(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            int key = num / 10;
            int value = num % 10;
            map.put(key, value);
        }
        dfs(map, nums[0] / 10, 0);
        return totalSum;
    }
    
    private void dfs(Map<Integer, Integer> map, int node, int sum) {
        int level = node / 10;
        int position = node % 10;
        int leftChild = (level + 1) * 10 + 2 * position - 1;
        int rightChild = leftChild + 1;
        
        sum += map.get(node);
        
        if (!map.containsKey(leftChild) && !map.containsKey(rightChild)) {
            totalSum += sum;
            return;
        }
        
        if (map.containsKey(leftChild)) {
            dfs(map, leftChild, sum);
        }
        
        if (map.containsKey(rightChild)) {
            dfs(map, rightChild, sum);
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 666 (Path Sum IV)?

This page provides optimized solutions for LeetCode problem 666 (Path Sum IV) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 666 (Path Sum IV)?

The time complexity for LeetCode 666 (Path Sum IV) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 666 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 666 in Java, C++, or Python.

Back to LeetCode Solutions