1. 程式人生 > >[leetcode]449. Serialize and Deserialize BST

[leetcode]449. Serialize and Deserialize BST

[leetcode]449. Serialize and Deserialize BST


Analysis

唉 感覺應該GG了,還是好好刷題看論文吧—— [每天刷題並不難0.0]

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

二叉樹的解碼和編碼,解碼的話就是用preOrder把所有節點值儲存起來,編碼的話就是反過來

Implement

/**
 * 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:

    // Encodes a tree to a single string.
string serialize(TreeNode* root) { string tree = ""; preOrder(tree, root); return tree; } void preOrder(string& tree, TreeNode* node){ if(node == NULL) return ; tree += to_string(node->val)+","; preOrder(tree, node->left)
; preOrder(tree, node->right); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(data == "") return NULL; vector<string> val1; string tmp = ""; for(int i=0; i<data.size(); i++){ if(data[i] == ','){ val1.push_back(tmp); tmp = ""; } else tmp += data[i]; } queue<int> q_val; for(string v:val1) q_val.push(stoi(v)); return build(q_val, INT_MIN, INT_MAX); } TreeNode* build(queue<int>& q, int low, int up){ if(q.empty()) return NULL; int vv = q.front(); if(vv < low || vv > up) return NULL; q.pop(); TreeNode* root = new TreeNode(vv); root->left = build(q, low, vv); root->right = build(q, vv, up); return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));