File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ ```java
2+ import java.io.*;
3+ import java.util.*;
4+
5+ public class Main {
6+ static int N;
7+ static List<Integer>[] tree;
8+ static boolean[] removed;
9+ static int deleteNode;
10+
11+ public static void main(String[] args) throws IOException {
12+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
14+ N = Integer.parseInt(br.readLine());
15+ tree = new ArrayList[N];
16+ removed = new boolean[N];
17+
18+ for (int i = 0; i < N; i++) {
19+ tree[i] = new ArrayList<>();
20+ }
21+
22+ StringTokenizer st = new StringTokenizer(br.readLine());
23+ int root = -1;
24+
25+ for (int i = 0; i < N; i++) {
26+ int parent = Integer.parseInt(st.nextToken());
27+ if (parent == -1) {
28+ root = i;
29+ } else {
30+ tree[parent].add(i);
31+ }
32+ }
33+
34+ deleteNode = Integer.parseInt(br.readLine());
35+
36+ removeNode(deleteNode);
37+
38+ if (removed[root]) {
39+ System.out.println(0);
40+ return;
41+ }
42+
43+ System.out.println(countLeaf(root));
44+ }
45+
46+ static void removeNode(int node) {
47+ removed[node] = true;
48+ for (int child : tree[node]) {
49+ removeNode(child);
50+ }
51+ }
52+
53+ static int countLeaf(int node) {
54+ if (removed[node]) return 0;
55+
56+ int childCount = 0;
57+ int leafCount = 0;
58+
59+ for (int child : tree[node]) {
60+ if (!removed[child]) {
61+ childCount++;
62+ leafCount += countLeaf(child);
63+ }
64+ }
65+
66+ return childCount == 0 ? 1 : leafCount;
67+ }
68+ }
69+ ```
You can’t perform that action at this time.
0 commit comments