# 序列化/反序列化二叉树，代码是自己写的

## 解法

    _30_
/    \
10    20
/     /  \
50    45  35

30 10 50 # # # 20 45 # # 35 # #

### 序列化二叉树

[cpp] view plain
1. void writeBinaryTree(BinaryTree *p, ostream &out)  //BinaryTree是二叉树结构体，typedef struct node BinaryTree.
2. {
3.   if (!p) {
4.     out << "# ";
5.   } else {
6.     out << p->data << " ";
7.     writeBinaryTree(p->left, out);
8.     writeBinaryTree(p->right, out);
9.   }
10. }

### 反序列化二叉树

[cpp] view plain
1. void readBinaryTree(BinaryTree *&p, ifstream &fin)
2. {
3.   int token;
4.   bool isNumber;
6.     return;
7.   if (isNumber) {
8.     p = newNode(token);         //newNode函数创建新结点，设定data为token，left和right初始化为NULL
11.   }
12. }

## 进一步思考

public class Treeserial {
public void toSerial(SearchNode node, StringBuffer sb) {
if (node == null) {
sb.append("#-");
return;
}
sb.append(node.getKey()).append("-");
toSerial(node.getLeftChild(), sb);
toSerial(node.getRightChild(), sb);
return;
}

public void toTree(SearchNode parentNode, Queue<String> queue) {
if (queue.isEmpty()) {
return;
}
String str = queue.poll();
//30-10-50-#-#-#-20-45-#-#-35-#-#-";
if (!"#".equals(str)) {
SearchNode left = new SearchNode(Integer.parseInt(str), str);
parentNode.setLeftChild(left);
toTree(left, queue);
if (queue.isEmpty()) {
return;
}
str = queue.poll();
if ("#".equals(str)) {
return;
} else {
SearchNode right = new SearchNode(Integer.parseInt(str), str);
parentNode.setRightChild(right);
toTree(right, queue);
}
} else {
if (queue.isEmpty()) {
return;
}
str = queue.poll();
if ("#".equals(str)) {
return;
} else {
SearchNode right = new SearchNode(Integer.parseInt(str), str);
parentNode.setRightChild(right);
toTree(parentNode, queue);
}
}
}

public static void main(String[] args) {
Treeserial t = new Treeserial();
/* SearchNode root = new SearchNode(30,"30");
root.setLeftChild(new SearchNode(10,"10"));
root.setRightChild(new SearchNode(20,"20"));
root.getLeftChild().setLeftChild(new SearchNode(50,"50"));
root.getRightChild().setLeftChild(new SearchNode(45,"45"));
root.getRightChild().setRightChild(new SearchNode(35,"35"));
StringBuffer sin = new StringBuffer();
t.toSerial(root,sin);
System.out.println(sin.toString());*/
String ss = "30-10-50-#-#-#-20-45-#-#-35-#-#-";
String[] arr = ss.split("-");
for (String s : arr) {
}