666. Path Sum IV
Если глубина дерева меньше 5, то это 木 можно представить в виде 配列а трехзначных чисел. Для каждого числа в этом 配列е:
Сотни представляют глубину d этого узла, где 1 <= d <= 4.
Десятки представляют позицию p этого узла на уровне, которому он принадлежит, где 1 <= p <= 8. Позиция соответствует позиции в полном бинарном дереве.
Единицы представляют значение v этого узла, где 0 <= v <= 9.
Дан 配列 возрастающих трехзначных чисел nums, представляющих бинарное 木 с глубиной меньше 5. return сумму всех путей от корня к листьям.
Гарантируется, что данный 配列 представляет собой валидное связанное бинарное 木.
例
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# 解法
照合済み/オリジナル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++ 解法
自動ドラフト、提出前に確認#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 解法
照合済み/オリジナル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 解法
照合済み/オリジナル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 解法
照合済み/オリジナル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
Создание структуры дерева:
Пройдите по 配列у nums и для каждого elementа создайте узел дерева.
Сохраните узлы в словаре для удобного доступа по их позиции.
Связывание узлов:
Пройдите по 配列у и свяжите узлы друг с другом, исходя из их позиции и глубины.
find левого и правого ребенка для каждого узла и установите соответствующие связи.
Подсчет суммы путей:
Выполните обход дерева (на例, используя DFS) и подсчитайте сумму всех путей от корня к листьям.
😎
Vacancies for this task
有効な求人 with overlapping task tags are 表示.