We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 73aea59 commit 5e650e7Copy full SHA for 5e650e7
1 file changed
swordoffer/SerializeTreeSolution.java
@@ -0,0 +1,45 @@
1
+/**
2
+ * 剑指Offer,序列化二叉树
3
+ */
4
+class TreeNode {
5
+ int val = 0;
6
+ TreeNode left = null;
7
+ TreeNode right = null;
8
+
9
+ public TreeNode(int val) {
10
+ this.val = val;
11
12
+ }
13
14
+}
15
16
+public class SerializeTreeSolution {
17
18
+ int index = -1;
19
20
+ String Serialize(TreeNode root) {
21
+ if (root == null) {
22
+ return "#";
23
24
25
+ return root.val + "," + Serialize(root.left) + "," + Serialize(root.right);
26
27
28
+ TreeNode Deserialize(String str) {
29
+ String[] s = str.split(",");
30
+ index++;
31
32
+ if (index > s.length) {
33
+ return null;
34
35
36
+ TreeNode node = null;
37
+ if ( !"#".equals(s[index]) ) {
38
+ node = new TreeNode(Integer.valueOf(s[index]));
39
+ node.left = Deserialize(str);
40
+ node.right = Deserialize(str);
41
42
43
+ return node;
44
45
0 commit comments