File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n)
2
+ // Space: O(n)
3
+
4
+ class Solution {
5
+ public:
6
+ int deleteTreeNodes (int nodes, vector<int >& parent, vector<int >& value) {
7
+ unordered_map<int , vector<int >> children;
8
+ for (int i = 1 ; i < parent.size (); ++i) {
9
+ children[parent[i]].emplace_back (i);
10
+ }
11
+ return dfs (value, &children, 0 ).second ;
12
+ }
13
+
14
+ private:
15
+ pair<int , int > dfs (const vector<int >& value,
16
+ unordered_map<int , vector<int >> *children,
17
+ int x) {
18
+ int total = value[x], count = 1 ;
19
+ for (const auto & y : (*children)[x]) {
20
+ const auto & [t, c] = dfs (value, children, y);
21
+ total += t;
22
+ count += t ? c : 0 ;
23
+ }
24
+ return {total, total ? count : 0 };
25
+ }
26
+ };
27
+
28
+
29
+ // Time: O(n)
30
+ // Space: O(n)
31
+ class Solution2 {
32
+ public:
33
+ int deleteTreeNodes (int nodes, vector<int >& parent, vector<int >& value) {
34
+ // assuming parent[i] < i for all i > 0
35
+ vector<int > result (nodes, 1 );
36
+ for (int i = nodes - 1 ; i >= 1 ; --i) {
37
+ value[parent[i]] += value[i];
38
+ result[parent[i]] += value[i] ? result[i] : 0 ;
39
+ }
40
+ return result[0 ];
41
+ }
42
+ };
You can’t perform that action at this time.
0 commit comments