Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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:
- string encoded = "";
- string inordered = "";
- void preorder(TreeNode* node) {
- if(node == NULL) {
- encoded += "NULL,";
- return ;
- }
- encoded += to_string(node->val) + ",";
- preorder(node -> left);
- preorder(node -> right);
- }
- // 1,2,NULL,NULL,3,4,NULL,NULL,5,NULL,NULL,
- // Encodes a tree to a single string.
- string serialize(TreeNode* root) {
- preorder(root);
- // cout << encoded << " ";
- return encoded;
- }
- queue<string> preprocess(string data) {
- string str = "";
- queue<string> q;
- for(int i = 0; i < data.size(); ++i) {
- if(data[i] == ',') {
- q.push(str);
- str = "";
- }
- else {
- str+= data[i];
- }
- }
- return q;
- }
- TreeNode* construct(queue<string> &q) {
- string str = q.front();
- q.pop();
- if(str == "NULL") {
- return NULL;
- }
- TreeNode* node = new TreeNode(stoi(str));
- node -> left = construct(q);
- node -> right = construct(q);
- return node;
- }
- // Decodes your encoded data to tree.
- TreeNode* deserialize(string data) {
- queue<string> q = preprocess(data);
- return construct(q);
- }
- };
- // Your Codec object will be instantiated and called as such:
- // Codec ser, deser;
- // TreeNode* ans = deser.deserialize(ser.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement