mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 18:23:52 +00:00
Update 37. 序列化二叉树.md
题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
+32
-24
@@ -1,6 +1,6 @@
|
||||
# 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)
|
||||
[Leetcode](https://leetcode.cn/problems/xu-lie-hua-er-cha-shu-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
@@ -9,31 +9,39 @@
|
||||
## 解题思路
|
||||
|
||||
```java
|
||||
private String deserializeStr;
|
||||
class Codec {
|
||||
|
||||
public String Serialize(TreeNode root) {
|
||||
if (root == null)
|
||||
return "#";
|
||||
return root.val + " " + Serialize(root.left) + " " + Serialize(root.right);
|
||||
}
|
||||
private String deserializeStr;
|
||||
|
||||
public TreeNode Deserialize(String str) {
|
||||
deserializeStr = str;
|
||||
return Deserialize();
|
||||
}
|
||||
// Encodes a tree to a single string.
|
||||
public String serialize(TreeNode root) {
|
||||
if (root == null) {
|
||||
return "#";
|
||||
}
|
||||
return root.val + " " + serialize(root.left) + " " + serialize(root.right);
|
||||
}
|
||||
|
||||
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;
|
||||
// Decodes your encoded data to tree.
|
||||
public TreeNode deserialize(String data) {
|
||||
deserializeStr = data;
|
||||
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.parseInt(node);
|
||||
TreeNode t = new TreeNode(val);
|
||||
t.left = deserialize();
|
||||
t.right = deserialize();
|
||||
return t;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user