File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-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 int dnode;
8+ static List<Integer > [] tree;
9+ static boolean [] visited;
10+ static int leafcount = 0 ;
11+ static int root;
12+
13+ public static void main (String [] args ) throws IOException {
14+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
15+ N = Integer . parseInt(br. readLine());
16+ tree = new ArrayList [N ];
17+ visited = new boolean [N ];
18+ for (int i = 0 ; i < N ; i++ ) {
19+ tree[i] = new ArrayList<> ();
20+ }
21+
22+ StringTokenizer st = new StringTokenizer (br. readLine());
23+ root = - 1 ;
24+ for (int i = 0 ; i < N ; i++ ) {
25+ int parent = Integer . parseInt(st. nextToken());
26+ if (parent == - 1 ) {
27+ root = i;
28+ } else {
29+ tree[parent]. add(i);
30+ }
31+ }
32+
33+ dnode = Integer . parseInt(br. readLine());
34+
35+ if (dnode == root) {
36+ System . out. println(0 );
37+ return ;
38+ }
39+
40+ dfs(root);
41+ System . out. println(leafcount);
42+ }
43+
44+ static void dfs (int now ) {
45+ visited[now] = true ;
46+ int childCount = 0 ;
47+
48+ for (int next : tree[now]) {
49+ if (next == dnode) continue ;
50+ if (! visited[next]) {
51+ dfs(next);
52+ childCount++ ;
53+ }
54+ }
55+
56+ if (childCount == 0 ) {
57+ leafcount++ ;
58+ }
59+ }
60+ }
61+ ```
You can’t perform that action at this time.
0 commit comments