C++ 代码
class Codec {
public:
// Encodes a tree to a single string.
vector<int> serialize(TreeNode* root) {
vector<int> os;
help_se(root, os);
return os;
}
void help_se(TreeNode* root, vector<int>& os){
if (root == NULL){
return;
}
else{
os.push_back(root->val);
help_se(root->left, os);
help_se(root->right, os);
}
}
TreeNode* deserialize(vector<int> data){
int pos = 0;
return help_de(data, pos, INT_MIN, INT_MAX);
}
TreeNode* help_de(vector<int>& is, int& pos, int minValue, int maxValue){
if (pos >= is.size() || minValue > maxValue){
return NULL;
}
int value = is[pos];
if (value < minValue || value > maxValue){
return NULL;
}
pos++;
TreeNode* node = new TreeNode(value);
node->left = help_de(is, pos, minValue, value);
node->right = help_de(is, pos, value, maxValue);
return node;
}
};
Python 代码
class Solution:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string.
"""
#TC: O(N)
#SC: O(N) (worst)
if not root:
return ""
data = []
def encoder(root):
data.append(root.val)
if root.left:
encoder(root.left)
if root.right:
encoder(root.right)
encoder(root)
print(data)
data = ','.join([str(s) for s in data])
return data
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree.
"""
if len(data) == 0:
return None
data = data.split(',')
data = [int(s) for s in data]
data.reverse()
def decoder(Max, Min):
if len(data) == 0:
return None
if not ( Min < data[-1] < Max):
return None
val = data[-1]
Node = TreeNode(val)
data.pop()
Node.left = decoder(val, Min)
Node.right = decoder(Max, val)
return Node
return decoder(sys.maxsize, -sys.maxsize)
作者:徐辰潇
链接:https://www.acwing.com/file_system/file/content/whole/index/content/476909/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
赞!