"Sword refers to offer" serialized binary tree, "Sword refers to offer" serialized

Source: Internet
Author: User

"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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.