FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/ThroneInheritance.java at master · anishLearnsToCode/leetcode-algorithms · GitHub
anishLearnsToCode
/
leetcode-algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
17
Star
98
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-algorithms
/
src
/
ThroneInheritance.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
63 lines (52 loc) · 1.65 KB
Breadcrumbs
leetcode-algorithms
/
src
/
ThroneInheritance.java
Copy path
File metadata and controls
63 lines (52 loc) · 1.65 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// https://leetcode.com/problems/throne-inheritance
// N = people in royal family
// birth() T: O(1)
// death() T: O(1)
// getInheritanceOrder T: O(N)
// S: O(N)
import
java
.
util
.
ArrayList
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
List
;
import
java
.
util
.
Map
;
public
class
ThroneInheritance
{
private
static
final
class
Person
{
private
final
String
name
;
private
boolean
isAlive
=
true
;
private
final
List
<
Person
>
children
=
new
ArrayList
<>();
Person
(
String
name
) {
this
.
name
=
name
;
}
void
markDead
() {
this
.
isAlive
=
false
;
}
void
addChild
(
Person
child
) {
this
.
children
.
add
(
child
);
}
}
private
final
Map
<
String
,
Person
>
royalFamily
=
new
HashMap
<>();
private
final
Person
king
;
public
ThroneInheritance
(
String
kingName
) {
king
=
new
Person
(
kingName
);
royalFamily
.
put
(
kingName
,
king
);
}
public
void
birth
(
String
parentName
,
String
childName
) {
Person
child
=
new
Person
(
childName
);
royalFamily
.
put
(
childName
,
child
);
royalFamily
.
get
(
parentName
).
addChild
(
child
);
}
public
void
death
(
String
name
) {
royalFamily
.
get
(
name
).
markDead
();
}
public
List
<
String
>
getInheritanceOrder
() {
final
List
<
String
>
names
=
new
ArrayList
<>();
getInheritanceOrder
(
king
,
names
);
return
names
;
}
public
void
getInheritanceOrder
(
Person
person
,
List
<
String
>
names
) {
if
(
person
==
null
)
return
;
if
(
person
.
isAlive
)
names
.
add
(
person
.
name
);
for
(
Person
child
:
person
.
children
) {
getInheritanceOrder
(
child
,
names
);
}
}
}
Back
|
FazBrowse Home
|
New Git URL