FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/code/lc297.java at master · mJackie/leetcode · GitHub
mJackie
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
135
Star
405
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
code
/
lc297.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
60 lines (55 loc) · 1.73 KB
Breadcrumbs
leetcode
/
code
/
lc297.java
Copy path
File metadata and controls
60 lines (55 loc) · 1.73 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
package
code
;
import
java
.
util
.
Arrays
;
import
java
.
util
.
Deque
;
import
java
.
util
.
LinkedList
;
/*
* 297. Serialize and Deserialize Binary Tree
* 题意:序列化,反序列化树
* 难度:Hard
* 分类:Tree, Design
* 思路:
* Tips:lc572 序列化的应用
*/
public
class
lc297
{
public
class
TreeNode
{
int
val
;
TreeNode
left
;
TreeNode
right
;
TreeNode
(
int
x
) {
val
=
x
; }
}
public
class
Codec
{
private
static
final
String
spliter
=
","
;
private
static
final
String
NN
=
"X"
;
// Encodes a tree to a single string.
public
String
serialize
(
TreeNode
root
) {
StringBuilder
sb
=
new
StringBuilder
();
buildString
(
root
,
sb
);
return
sb
.
toString
();
}
private
void
buildString
(
TreeNode
node
,
StringBuilder
sb
) {
if
(
node
==
null
) {
sb
.
append
(
NN
).
append
(
spliter
);
}
else
{
sb
.
append
(
node
.
val
).
append
(
spliter
);
buildString
(
node
.
left
,
sb
);
buildString
(
node
.
right
,
sb
);
}
}
// Decodes your encoded data to tree.
public
TreeNode
deserialize
(
String
data
) {
Deque
<
String
>
nodes
=
new
LinkedList
<>();
nodes
.
addAll
(
Arrays
.
asList
(
data
.
split
(
spliter
)));
//split
return
buildTree
(
nodes
);
}
private
TreeNode
buildTree
(
Deque
<
String
>
nodes
) {
String
val
=
nodes
.
remove
();
if
(
val
.
equals
(
NN
))
return
null
;
else
{
TreeNode
node
=
new
TreeNode
(
Integer
.
valueOf
(
val
));
node
.
left
=
buildTree
(
nodes
);
node
.
right
=
buildTree
(
nodes
);
return
node
;
}
}
}
}
Back
|
FazBrowse Home
|
New Git URL