·  阅读 308

# 37.序列化二叉树

## 题目描述

{8,6,10,5,7,9,11}

{8,6,10,5,7,9,11}

## 思路 & 解答

``````import java.util.LinkedList;
import java.util.Queue;
public class Solution {
int index = -1;
String Serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
if(root == null) {
sb.append("#,");
return sb.toString();
}
sb.append(root.val + ",");
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));
return sb.toString();
}

TreeNode Deserialize(String str) {
index++;
String[] strs = str.split(",");
TreeNode node = null;
if(!strs[index].equals("#")) {
node = new TreeNode(Integer.valueOf(strs[index]));
node.left = Deserialize(str);
node.right = Deserialize((str));
}
return node;
}
}

`C++` 代码如下：

``````class Solution {
public:
char *Serialize(TreeNode *root) {
if (!root) {
return "#";
}
string res = to_string(root->val);
res.push_back(',');
char *left = Serialize(root->left);
char *right = Serialize(root->right);
char *ret = new char[strlen(left) + strlen(right) + res.size()];

strcpy(ret, res.c_str());
strcat(ret, left);
strcat(ret, right);
return ret;
}

TreeNode *deseri(char *&str) {
if (*str == '#') {
++str;
return nullptr;
}

int num = 0;
while (*str != ',') {
num = num * 10 + (*str - '0');
++str;
}
++str;
TreeNode *root = new TreeNode(num);
root->left = deseri(str);
root->right = deseri(str);
return root;
}

TreeNode *Deserialize(char *str) {
return deseri(str);
}
};

【作者简介】