"Sword refers to offer" serialized binary tree, "Sword refers to offer" serialized
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84? Rp = 4 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Implement two functions for serialization and deserialization of Binary Trees respectively.
Ideas
Binary tree traversal should also be done a lot, so it is not difficult to recursively implement the pre-order traversal and the re-build tree of the string obtained from the pre-order traversal, the main problem with this question is our control over the input stream.
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Solution{public:char* Serialize(TreeNode *root){stringstream Str;Serialize(root,Str);const char *c_Str = Str.str().c_str();char *serial = new char [strlen(c_Str)+1];strcpy(serial,c_Str);return serial;}TreeNode* Deserialize(char *str){if(str==nullptr)return nullptr;stringstream ss(str);return Deserialize(ss);}void Serialize(TreeNode *root,stringstream& out){if(root==nullptr){out<<"#"<<endl;return ;}out<<root->val<<endl;Serialize(root->left,out);Serialize(root->right,out);}TreeNode* Deserialize(stringstream& in){int val;if(getNumber(in,val)){TreeNode *p = new TreeNode(val);p->left = Deserialize(in);p->right = Deserialize(in);return p;}return nullptr;}bool getNumber(stringstream& in,int& val){char buf[32];in>>buf;if(buf[0]=='#') return false;val = atoi(buf);return true;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source