3
代碼如下:
鏈接:https://www.nowcoder.com/questionTerminal/4faa2d4849fa4627aa6d32a2e50b5b25
來源:牛客網
import
java.util.HashMap;
import
java.util.Scanner;
public
class
Main {
public
static
void
main(String[] args) {
Scanner scanner =
new
Scanner(System.in);
int
n = scanner.nextInt();
String result =
""
;
HashMap<Integer, Integer> deep =
new
HashMap<>();
HashMap<Integer, Integer> childNum =
new
HashMap<>();
deep.put(
0
,
1
);
childNum.put(
0
,
0
);
int
max =
1
;
int
myDeep =
0
;
for
(
int
i =
0
; i < n -
1
; i++) {
int
parent = scanner.nextInt();
int
num = scanner.nextInt();
if
(!deep.containsKey(parent) || childNum.get(parent) >=
2
) {
continue
;
}
myDeep = deep.get(parent) +
1
;
deep.put(num, myDeep);
childNum.put(parent, (childNum.get(parent) +
1
));
childNum.put(num,
0
);
if
(myDeep > max) {
max = myDeep;
}
}
System.out.println(max);
}
}