-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeSerialization_1.java
More file actions
70 lines (59 loc) · 1.91 KB
/
BinaryTreeSerialization_1.java
File metadata and controls
70 lines (59 loc) · 1.91 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
/**
* ----------------------------------------------------------------------------
Binary Tree Serialization (lintcode)
- Design an algorithm and write code to serialize and deserialize a binary
tree
- Writing the tree toa file is called ``serialization''
- Reading back from the file to reconstruct the exact same binary tree is
``deserialization''
* ----------------------------------------------------------------------------
*/
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
/**
* Preorder DFS Serialization
* The problem of BFS is that when the tree is unbalanced, we need to store
* quite a lot of nulls in each level
*/
class Solution {
public String serialize(TreeNode root) {
// write your code here
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
}
private void serialize(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append("#,");
return; // XXXX miss this first time
}
sb.append(root.val + ",");
serialize(root.left, sb);
serialize(root.right, sb);
}
public TreeNode deserialize(String data) {
// write your code here
StringBuilder sb = new StringBuilder(data);
return deserialize(sb);
}
private TreeNode deserialize(StringBuilder sb) {
int index = sb.indexOf(",");
String sub = sb.substring(0, index);
sb.delete(0, index+1);
if (sub.equals("#"))
return null;
TreeNode root = new TreeNode(Integer.valueOf(sub));
root.left = deserialize(sb);
root.right = deserialize(sb);
return root;
}
}