-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay82.java
More file actions
77 lines (68 loc) · 2.42 KB
/
Day82.java
File metadata and controls
77 lines (68 loc) · 2.42 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
public class Day82 {
public String serialize(TreeNode root) {
if (root == null) return "";
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node != null) {
sb.append(node.val).append(" ");
queue.offer(node.left);
queue.offer(node.right);
} else {
sb.append("-1 ");
}
}
return sb.toString().trim();
}
public TreeNode deserialize(String data) {
if (data == null || data.isEmpty()) return null;
String[] values = data.split(" ");
TreeNode root = new TreeNode(Integer.parseInt(values[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
for (int i = 1; i < values.length; i++) {
TreeNode parent = queue.poll();
if (!values[i].equals("-1")) {
TreeNode left = new TreeNode(Integer.parseInt(values[i]));
parent.left = left;
queue.offer(left);
}
if (!values[++i].equals("-1")) {
TreeNode right = new TreeNode(Integer.parseInt(values[i]));
parent.right = right;
queue.offer(right);
}
}
return root;
}
public void inorderTraversal(TreeNode root) {
if (root != null) {
inorderTraversal(root.left);
System.out.print(root.val + " ");
inorderTraversal(root.right);
}
}
public static void main(String[] args) {
BinaryTreeSerialization bt = new BinaryTreeSerialization();
TreeNode root = new TreeNode(1);
root.right = new TreeNode(3);
root.right.left = new TreeNode(2);
String serializedTree = bt.serialize(root);
System.out.println("Serialized tree: " + serializedTree);
TreeNode deserializedRoot = bt.deserialize(serializedTree);
// Print inorder traversal of deserialized binary tree
System.out.print("Inorder traversal of deserialized tree: ");
bt.inorderTraversal(deserializedRoot);
}
}