题目
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
根据数组构建二叉树:用队列,依次取一个结点然后按数组顺序构建左右孩子
根据数组nums[i]构建二叉树:
- 将根结点放入队列,同时记录已构造结点个数cnt=1;
- 然后每次从队列中取出一个结点,构建其左、右孩子,再给放进队列。
- 左右孩子的取值就是nums[cnt]
- 最后返回根结点
注意字符串转数字stoi(str)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
//二叉树层序遍历。输出格式:[1,2,3,null,null,4,5]。
//注意数字转字符串 to_string(i)
if( root==NULL ){
return "null";
}
queue<TreeNode*> que;
//根结点
que.push(root);
string output = "";
while( !que.empty() ){
int size = que.size();
for(int i=0; i<size; i++){
TreeNode* node = que.front();
que.pop();
if( node == NULL ){//当前结点为空
output += "null,";
}else{
output += to_string(node->val) + ",";
//不管左右子树是否为空,都要放进队列
que.push( node->left );
que.push( node->right );
}
}
}
//从0开始的out.length()-1个字符
output = "[" + output.substr(0,output.length()-1) + "]";
return output;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
//字符串分割,输入格式为:[1,2,3,null,null,4,5]
if( data=="" || data=="[]" || data=="null"){ //注意这里判断字符串为null!!调试了好久!
return NULL;
}
//按逗号分割
vector<string> words;
string temp = "";
for(int i=1; i<=data.length()-2; i++){//去除了格式首尾的[]
if(data[i]==','){
words.push_back(temp);
temp = "";
}else{
temp += data[i];
}
}
words.push_back(temp);
//开始构建二叉树:将根结点放入队列,同时记录已构造结点个数cnt=1;然后每次从队列中取出一个结点,它的左孩子是arr[cnt]构建的结点,它的右孩子是arr[cnt+1]构建的结点
//注意字符串转数字stoi(str)
if( words[0]=="" || words[0]=="null" ){
return NULL;
}
queue<TreeNode *> que;
int cnt = 0;
//根结点
TreeNode *root = new TreeNode(stoi(words[0]));
que.push(root);
cnt++; //已构造结点的个数
//每次从队列中取出一个结点,创建其左右孩子,然后把左右孩子放入队列
while( cnt<words.size() && !que.empty() ){
TreeNode *node = que.front();
que.pop();
//左孩子
if( cnt<words.size() && words[cnt]!="null" ){
node->left = new TreeNode(stoi(words[cnt])); //左右孩子的取值跟已构造结点的个数有关
que.push(node->left);
}
cnt++;
//右孩子
if( cnt<words.size() && words[cnt]!="null"){
node->right = new TreeNode(stoi(words[cnt])); //左右孩子的取值跟已构造结点的个数有关
que.push(node->right);
}
cnt++;
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));