对于一般的二叉树,我们对其进行序列化和反序列化,可以在前序遍历的基础上通过将其所有节点,包括空结点输出的方式保存下来。由于二叉搜索树定义,只需要其前序遍历,就可以还原整个二叉树。还原的时候由两种方法,一种是排序构造中序遍历,通过中序遍历和前序遍历还原二叉树。还有一种是维护一个范围,在前序遍历的基础上,递归的完成构建。这里选择方案二。
其中解析字符串的过程使用sstream,不必在这里手动实现解析。
/**
* 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:
void dfs(TreeNode* root, string& s){
if(root == nullptr){
return;
}
s += to_string(root->val) + " ";
dfs(root->left, s);
dfs(root->right, s);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s;
dfs(root, s);
return s;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<int> preorder;
stringstream ssin(data);
int x = 0;
while(ssin >> x){
preorder.push_back(x);
}
int u = 0;
return helper(preorder, u, INT_MIN, INT_MAX);
}
TreeNode* helper(vector<int>& preorder, int& u, int min, int max){
if(u >= preorder.size() || preorder[u] > max || preorder[u] < min){
return nullptr;
}
auto root = new TreeNode(preorder[u++]);
root->left = helper(preorder, u, min, root->val);
root->right = helper(preorder, u, root->val, max);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;
优雅的Python实现:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string.
"""
def postorder(root):
return [root.val] + postorder(root.left) + postorder(root.right) if root != None else []
return " ".join(map(str, postorder(root)))
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree.
"""
def helper(lower = float('-inf'), upper = float('inf')):
if not data or data[0] < lower or data[0] > upper:
return None
val = data.pop(0)
root = TreeNode(val)
root.left = helper(lower, val)
root.right = helper(val, upper)
return root
data = list(map(int, data.split()))
return helper()
# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans