2019-11-02 12:07:41 +08:00
|
|
|
|
# 37. 序列化二叉树
|
|
|
|
|
|
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13&tqId=11214&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
请实现两个函数,分别用来序列化和反序列化二叉树。
|
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
private String deserializeStr;
|
|
|
|
|
|
|
|
|
|
public String Serialize(TreeNode root) {
|
|
|
|
|
if (root == null)
|
|
|
|
|
return "#";
|
|
|
|
|
return root.val + " " + Serialize(root.left) + " " + Serialize(root.right);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public TreeNode Deserialize(String str) {
|
|
|
|
|
deserializeStr = str;
|
|
|
|
|
return Deserialize();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private TreeNode Deserialize() {
|
|
|
|
|
if (deserializeStr.length() == 0)
|
|
|
|
|
return null;
|
|
|
|
|
int index = deserializeStr.indexOf(" ");
|
|
|
|
|
String node = index == -1 ? deserializeStr : deserializeStr.substring(0, index);
|
|
|
|
|
deserializeStr = index == -1 ? "" : deserializeStr.substring(index + 1);
|
|
|
|
|
if (node.equals("#"))
|
|
|
|
|
return null;
|
|
|
|
|
int val = Integer.valueOf(node);
|
|
|
|
|
TreeNode t = new TreeNode(val);
|
|
|
|
|
t.left = Deserialize();
|
|
|
|
|
t.right = Deserialize();
|
|
|
|
|
return t;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|