666. Path Sum IV

El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

Если глубина дерева меньше 5, то это árbol можно представить в виде arregloа трехзначных чисел. Для каждого числа в этом arregloе:

Сотни представляют глубину d этого узла, где 1 <= d <= 4.

Десятки представляют позицию p этого узла на уровне, которому он принадлежит, где 1 <= p <= 8. Позиция соответствует позиции в полном бинарном дереве.

Единицы представляют значение v этого узла, где 0 <= v <= 9.

Дан arreglo возрастающих трехзначных чисел nums, представляющих бинарное árbol с глубиной меньше 5. return сумму всех путей от корня к листьям.

Гарантируется, что данный arreglo представляет собой валидное связанное бинарное árbol.

Ejemplo

Input: nums = [113,215,221]

Output: 12

Explanation: The tree that the list represents is shown.

The path sum is (3 + 5) + (3 + 1) = 12.

C# solución

coincidente/original
public class Solution {
    public int PathSum(int[] nums) {
        var tree = new Dictionary<int, int>();
        
        foreach (int num in nums) {
            int depth = num / 100;
            int pos = (num / 10) % 10;
            int val = num % 10;
            tree[depth * 10 + pos] = val;
        }
        
        return Dfs(tree, 1, 1, 0);
    }
    
    private int Dfs(Dictionary<int, int> tree, int depth, int pos, int currentSum) {
        int key = depth * 10 + pos;
        if (!tree.ContainsKey(key)) {
            return 0;
        }
        currentSum += tree[key];
        int leftChild = (depth + 1) * 10 + 2 * pos - 1;
        int rightChild = (depth + 1) * 10 + 2 * pos;
        if (!tree.ContainsKey(leftChild) && !tree.ContainsKey(rightChild)) {
            return currentSum;
        }
        return Dfs(tree, depth + 1, 2 * pos - 1, currentSum) + Dfs(tree, depth + 1, 2 * pos, currentSum);
    }
}

C++ solución

borrador automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int PathSum(vector<int>& nums) {
        var tree = new unordered_map<int, int>();
        
        foreach (int num in nums) {
            int depth = num / 100;
            int pos = (num / 10) % 10;
            int val = num % 10;
            tree[depth * 10 + pos] = val;
        }
        
        return Dfs(tree, 1, 1, 0);
    }
    
    private int Dfs(unordered_map<int, int> tree, int depth, int pos, int currentSum) {
        int key = depth * 10 + pos;
        if (!tree.count(key)) {
            return 0;
        }
        currentSum += tree[key];
        int leftChild = (depth + 1) * 10 + 2 * pos - 1;
        int rightChild = (depth + 1) * 10 + 2 * pos;
        if (!tree.count(leftChild) && !tree.count(rightChild)) {
            return currentSum;
        }
        return Dfs(tree, depth + 1, 2 * pos - 1, currentSum) + Dfs(tree, depth + 1, 2 * pos, currentSum);
    }
}

Java solución

coincidente/original
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int pathSum(int[] nums) {
        Map<Integer, Integer> tree = new HashMap<>();
        
        for (int num : nums) {
            int depth = num / 100;
            int pos = (num / 10) % 10;
            int val = num % 10;
            tree.put(depth * 10 + pos, val);
        }
        
        return dfs(tree, 1, 1, 0);
    }
    
    private int dfs(Map<Integer, Integer> tree, int depth, int pos, int currentSum) {
        int key = depth * 10 + pos;
        if (!tree.containsKey(key)) {
            return 0;
        }
        currentSum += tree.get(key);
        int leftChild = (depth + 1) * 10 + 2 * pos - 1;
        int rightChild = (depth + 1) * 10 + 2 * pos;
        if (!tree.containsKey(leftChild) && !tree.containsKey(rightChild)) {
            return currentSum;
        }
        return dfs(tree, depth + 1, 2 * pos - 1, currentSum) + dfs(tree, depth + 1, 2 * pos, currentSum);
    }
}

JavaScript solución

coincidente/original
var pathSum = function(nums) {
    let tree = new Map();
    
    for (let num of nums) {
        let depth = Math.floor(num / 100);
        let pos = Math.floor(num / 10) % 10;
        let val = num % 10;
        tree.set(depth * 10 + pos, val);
    }
    
    return dfs(tree, 1, 1, 0);
};

function dfs(tree, depth, pos, currentSum) {
    let key = depth * 10 + pos;
    if (!tree.has(key)) {
        return 0;
    }
    currentSum += tree.get(key);
    let leftChild = (depth + 1) * 10 + 2 * pos - 1;
    let rightChild = (depth + 1) * 10 + 2 * pos;
    if (!tree.has(leftChild) && !tree.has(rightChild)) {
        return currentSum;
    }
    return dfs(tree, depth + 1, 2 * pos - 1, currentSum) + dfs(tree, depth + 1, 2 * pos, currentSum);
}

Go solución

coincidente/original
func pathSum(nums []int) int {
    tree := make(map[int]int)
    
    for _, num := range nums {
        depth := num / 100
        pos := (num / 10) % 10
        val := num % 10
        tree[depth*10+pos] = val
    }
    
    return dfs(tree, 1, 1, 0)
}

func dfs(tree map[int]int, depth, pos, currentSum int) int {
    key := depth*10 + pos
    if _, exists := tree[key]; !exists {
        return 0
    }
    currentSum += tree[key]
    leftChild := (depth + 1) * 10 + 2*pos - 1
    rightChild := (depth + 1) * 10 + 2*pos
    if _, leftExists := tree[leftChild]; !leftExists && !tree[rightChild] {
        return currentSum
    }
    return dfs(tree, depth+1, 2*pos-1, currentSum) + dfs(tree, depth+1, 2*pos, currentSum)
}

Algorithm

Создание структуры дерева:

Пройдите по arregloу nums и для каждого elementа создайте узел дерева.

Сохраните узлы в словаре для удобного доступа по их позиции.

Связывание узлов:

Пройдите по arregloу и свяжите узлы друг с другом, исходя из их позиции и глубины.

find левого и правого ребенка для каждого узла и установите соответствующие связи.

Подсчет суммы путей:

Выполните обход дерева (наEjemplo, используя DFS) и подсчитайте сумму всех путей от корня к листьям.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.