1273. Delete Tree Nodes

LeetCode medium original: C# #array #csharp #graph #hash-table #leetcode #medium #tree
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

트리, укорененное в узле 0, заgiven следующим образом: количество узлов - nodes; значение i-го узла - value[i]; родитель i-го узла - parent[i]. Удалите все поддеревья, сумма значений узлов которых равна нулю. return количество оставшихся узлов в дереве.

예제:

Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]

Output: 2

C# 해법

매칭됨/원본
using System;
using System.Collections.Generic;
public class Solution {
    public int DeleteTreeNodes(int nodes, int[] parent, int[] value) {
        var tree = new Dictionary<int, List<int>>();
        for (int i = 0; i < nodes; i++) {
            if (!tree.ContainsKey(parent[i])) tree[parent[i]] = new List<int>();
            tree[parent[i]].Add(i);
        }
        (int, int) Dfs(int node) {
            int totalSum = value[node];
            int totalCount = 1;
            if (tree.ContainsKey(node)) {
                foreach (int child in tree[node]) {
                    var (childSum, childCount) = Dfs(child);
                    totalSum += childSum;
                    totalCount += childCount;
                }
            }
            return totalSum == 0 ? (0, 0) : (totalSum, totalCount);
        }
        return Dfs(0).Item2;
    }
}

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 DeleteTreeNodes(int nodes, vector<int>& parent, vector<int>& value) {
        var tree = new unordered_map<int, List<int>>();
        for (int i = 0; i < nodes; i++) {
            if (!tree.count(parent[i])) tree[parent[i]] = new List<int>();
            tree[parent[i]].push_back(i);
        }
        (int, int) Dfs(int node) {
            int totalSum = value[node];
            int totalCount = 1;
            if (tree.count(node)) {
                foreach (int child in tree[node]) {
                    var (childSum, childCount) = Dfs(child);
                    totalSum += childSum;
                    totalCount += childCount;
                }
            }
            return totalSum == 0 ? (0, 0) : (totalSum, totalCount);
        }
        return Dfs(0).Item2;
    }
}

Java 해법

매칭됨/원본
import java.util.*;

public class Solution {
    public int deleteTreeNodes(int nodes, int[] parent, int[] value) {
        Map<Integer, List<Integer>> tree = new HashMap<>();
        for (int i = 0; i < nodes; i++) {
            tree.computeIfAbsent(parent[i], k -> new ArrayList<>()).add(i);
        }

        return dfs(0, tree, value)[1];
    }

    private int[] dfs(int node, Map<Integer, List<Integer>> tree, int[] value) {
        int totalSum = value[node];
        int totalCount = 1;
        if (tree.containsKey(node)) {
            for (int child : tree.get(node)) {
                int[] childResult = dfs(child, tree, value);
                totalSum += childResult[0];
                totalCount += childResult[1];
            }
        }
        if (totalSum == 0) {
            return new int[]{0, 0};
        }
        return new int[]{totalSum, totalCount};
    }
}

JavaScript 해법

매칭됨/원본
var deleteTreeNodes = function(nodes, parent, value) {
    let tree = new Map();
    for (let i = 0; i < nodes; i++) {
        if (!tree.has(parent[i])) tree.set(parent[i], []);
        tree.get(parent[i]).push(i);
    }

    function dfs(node) {
        let totalSum = value[node];
        let totalCount = 1;
        if (tree.has(node)) {
            for (let child of tree.get(node)) {
                let [childSum, childCount] = dfs(child);
                totalSum += childSum;
                totalCount += childCount;
            }
        }
        return totalSum === 0 ? [0, 0] : [totalSum, totalCount];
    }

    return dfs(0)[1];
};

Python 해법

매칭됨/원본
def deleteTreeNodes(nodes, parent, value):
    from collections import defaultdict, deque
    
    tree = defaultdict(list)
    for i in range(nodes):
        if parent[i] != -1:
            tree[parent[i]].append(i)
    
    def dfs(node):
        total_sum = value[node]
        total_count = 1
        for child in tree[node]:
            child_sum, child_count = dfs(child)
            total_sum += child_sum
            total_count += child_count
        if total_sum == 0:
            return 0, 0
        return total_sum, total_count
    
    return dfs(0)[1]

Go 해법

매칭됨/원본
func deleteTreeNodes(nodes int, parent []int, value []int) int {
    tree := make(map[int][]int)
    for i := 0; i < nodes; i++ {
        tree[parent[i]] = append(tree[parent[i]], i)
    }

    var dfs func(node int) (int, int)
    dfs = func(node int) (int, int) {
        totalSum := value[node]
        totalCount := 1
        for _, child := range tree[node] {
            childSum, childCount := dfs(child)
            totalSum += childSum
            totalCount += childCount
        }
        if totalSum == 0 {
            return 0, 0
        }
        return totalSum, totalCount
    }

    _, count := dfs(0)
    return count
}

Algorithm

Постройте 트리 из заданных узлов, значений и родителей.

Используйте постфиксный обход для вычисления суммы значений в каждом поддереве и помечайте узлы для удаления, если их сумма равна нулю.

Удалите отмеченные узлы и их поддеревья и return количество оставшихся узлов.

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.