思路:
1、d对于经常调用string 与 int之间转换的代码 一定要建立函数 美观 好使;
2、 先序遍历,保存格式为: 数字+“ ” 空节点为 “# ”
3、 将string处理为queue 方便处理节点后直接弹出
4、遍历queue中的节点,遍历到时弹出,为“#”返回空,否则按先序遍历的方式递归遍历
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
int strtoint(string &svalue){
stringstream ss;
ss << svalue;
int ivalue;
ss >> ivalue;
return ivalue;
}
string inttostr(int &ivalue){
stringstream ss;
ss << ivalue;
string svalue;
ss >> svalue;
return svalue;
}
string serialize(TreeNode * root) {
if(root == NULL) //基本情况 而且处理了头结点为空的问题 很6
return "# ";
string svalue = inttostr(root->val);
string res = svalue+" ";
res += serialize(root->left);
res += serialize(root->right);
return res;
}
TreeNode * deserialize(string &data) {
// write your code here
queue<string> p;
stringstream input(data);
string temp;
while(input >> temp){
p.push(temp);
temp.clear();
}
return deserializehelp(p);
}
TreeNode* deserializehelp(queue<string> &p){
string svalue = p.front();
p.pop();
if(svalue == "#"){
return NULL;
}
int ivalue = strtoint(svalue);
TreeNode* root = new TreeNode(ivalue);
root->left = deserializehelp(p);
root->right = deserializehelp(p);
return root;
}
};
刷题:https://www.lintcode.com/problem/serialize-and-deserialize-binary-tree/
网友评论