Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9a1bef9

Browse files
Create 2385-amount-of-time-for-binary-tree-to-be-infected.java
1 parentde257c5 commit9a1bef9

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*--------------------------
2+
Time Complexity: O(n)
3+
Space Complexity: O(n)
4+
---------------------------*/
5+
classSolution {
6+
publicintamountOfTime(TreeNoderoot,intstart) {
7+
Map<Integer,List<Integer>>g =treeTograph(root);
8+
inttime =0;
9+
Queue<Integer>q =newLinkedList<>();
10+
Set<Integer>visited =newHashSet<>();
11+
q.add(start);
12+
visited.add(start);
13+
14+
while(!q.isEmpty()){
15+
intsize =q.size();
16+
for (inti =0;i <size;i++) {
17+
intcurr =q.poll();
18+
for (intneighbour :g.get(curr)) {
19+
if (!visited.contains(neighbour)) {
20+
q.add(neighbour);
21+
visited.add(neighbour);
22+
}
23+
}
24+
}
25+
time++;
26+
}
27+
returntime-1;
28+
}
29+
publicHashMap<Integer,List<Integer>>treeTograph(TreeNoderoot) {
30+
HashMap<Integer,List<Integer>>graph =newHashMap<>();
31+
buildGraph(root,graph);
32+
returngraph;
33+
}
34+
35+
privatevoidbuildGraph(TreeNodenode,HashMap<Integer,List<Integer>>graph) {
36+
if (node ==null) {
37+
return;
38+
}
39+
40+
graph.putIfAbsent(node.val,newArrayList<>());
41+
42+
if (node.left !=null) {
43+
graph.get(node.val).add(node.left.val);
44+
graph.putIfAbsent(node.left.val,newArrayList<>());
45+
graph.get(node.left.val).add(node.val);
46+
buildGraph(node.left,graph);
47+
}
48+
49+
if (node.right !=null) {
50+
graph.get(node.val).add(node.right.val);
51+
graph.putIfAbsent(node.right.val,newArrayList<>());
52+
graph.get(node.right.val).add(node.val);
53+
buildGraph(node.right,graph);
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp