链接:
449. 序列化和反序列化二叉搜索树
题意:
把一个二叉搜索树变成字符串,还要能变回来
解:
和剑指 Offer 37. 序列化二叉树差不多,那个是二叉树的序列化/反序列化-Hard
直接CV了,懒: (`
如果是二叉搜索树的话,就相当于知道了中序遍历,前序/后序弄一个就行
实际代码:
string int2string(int x)
{string ret;if(x==0) return "0";while(x){ret=char('0'+x%10)+ret;x/=10;}return ret;
}
int string2int(string s)
{int ret=0;for(auto &ch:s){ret=ret*10+int(ch-'0');}return ret;
}
void node2string(string& s,TreeNode* root)
{s.append(int2string(root->val));if(root->left!=nullptr){s.append(",");node2string(s,root->left);}else s.append(",N");if(root->right!=nullptr){s.append(",");node2string(s,root->right);}else s.append(",N");
}
string serialize(TreeNode* root)
{string tree;if(root==nullptr) return tree;node2string(tree,root);//cout<<"tree:"<<tree<<endl; return tree;
}
void string2node(TreeNode* root,string& data)
{string s;int r=0;while(r<data.size() && data[r]!=',') r++;s=data.substr(0,r);data.erase(0,min(r+1,int(data.size())));if(s=="N") root->left=nullptr;else{root->left=new TreeNode(string2int(s));string2node(root->left,data);}r=0;while(r<data.size() && data[r]!=',') r++;s=data.substr(0,r);data.erase(0,min(r+1,int(data.size())));if(s=="N") root->right=nullptr;else{root->right=new TreeNode(string2int(s));string2node(root->right,data);}
}
TreeNode* deserialize(string data)
{TreeNode* newHead=nullptr;if(data.empty()) return newHead;string s;int r=0;while(r<data.size() && data[r]!=',') r++;s=data.substr(0,r);data.erase(0,min(r+1,int(data.size())));newHead=new TreeNode(string2int(s));string2node(newHead,data);return newHead;
}
限制:
- 树中节点数范围是
[0, 104]
0 <= Node.val <= 104
- 题目数据 保证 输入的树是一棵二叉搜索树。